Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

using malloc and printing amount of memory used

Status
Not open for further replies.

Seijuro

Programmer
Oct 8, 2003
10
US
I wanted to used a loop that mallocs a memory block of some size and then prints the total amount of memory used until it malloc returns a 0 or until it stops and crashes. This is what I have so far:

Code:
int *allocated;
	int n;

	allocated = malloc(3 * sizeof(int));
	
	for(n = 0; n < 3; n++);
	{
		printf (&quot;%d\n&quot;, n);
	}
	
	free(allocated);

	else
	printf(&quot;0&quot;);

Is this right?? Any help would be appreciated!!
 
Depending on which OS you use , you can get 0 or null returned by malloc() but also you can wait some time to get 0 or crash because when if not enough memory then will use virtual memory , so swap processes take place with pages from the HDD (for example on Windows you will get first an Warning that your machine are slow in the resources and ask you to stop some applications!).
Do you want to test if malloc() is working Okay ?

-obislavu-
 
Yeah I want to know if the code I have actually works or if you know how to modify it to work like that.
 
Code:
int fill()
{


	double *allocated;
	int n;

	if (allocated != NULL)
	{
	while (malloc (n *sizeof (double)))
	{
		allocated += 1;

		printf (&quot;Total Amount of Memory Used: %d \n&quot;, allocated);

	}free(allocated);
	return 0;
	}
	else{
	printf(&quot;Memory Not allocated\n&quot;);
	return 1;
	}

}
 
Sorry, but the above code is not right:
- double *allocated; // must assign NULL or something else
- n not initialized
- what is allocated by malloc() should be cast to (double*) and assigned to allocated if that you want.
- allocated+= 1; is not measuring the memory allocated it is an arithmetic pointer operation

-obislavu-

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top