In my C program, I've allocated memory using this:
C Code:
printf("Sorting.\nSort how many numbers? ");
scanf("%ld", &n); //get input for number of numbers
int *pIntArray; //declare pointer, which will point to first element
pIntArray = (int *) malloc (sizeof(int) * n); //allocate enough memory for 'n' ints, and point pIntArray at the first one
I know I'm meant to free the memory once I'm done with it, but when I call free(), do I only need to call it once, using pIntArray as the argument? Or do I need to loop through pIntArray to pIntArray + n - 1 and free every one of my 'elements'? Oh and after free()ing, should I set pIntArray to NULL?
On a side note, if I don't free() the memory, creating a memory leak, when is the memory eventually returned to the pool? When the program ends? When the computer is shut down? Some other time?
You only need to call it once. Free assigns the pointer NULL automatically, but theres alot of code/people out there that say its good practice to set pointers to null anyway.. I guess its just personal preference.
Memory being returned to the pool is really quite undefined. If you force a process to close in Windows, theres no guarantee given out by Windows that all of the memory will be freed properly (especially with dangling pointers). The only sure-way for it to happen is clearing the RAM completely.. which, is a shutdown/reboot.
Free assigns the pointer NULL automatically...
chem
Remind me never to run any of your apps ...
free() accepts a void pointer, which is basically copied onto the stack when the call is made, therefore it is not possible for free() to set the original pointer to null. It would have to be a pointer to the pointer if that were the case.
Therefore...
Last edited by wossname; Mar 18th, 2008 at 07:29 AM.
free() accepts a void pointer, which is basically copied onto the stack when the call is made, therefore it is not possible for free() to set the original pointer to null. It would have to be a pointer to the pointer if that were the case.
Therefore...
Massive typo on this sheet from my game dev course.. it explains free. Perhaps its on certain infrastructures? My game dev course was aimed at PS2 development..