In C and C++, it is the responsibility of the programmer to make sure
that dynamically allocated memory is handled correctly. You must
deallocate memory that is no longer needed. You must make sure that
pointers which were pointing to the deallocated memory are set to NULL or
are set to some other valid (allocated) memory.
Example in C
#include <stdio.h>
#include <stdlib.h>
/* prototypes in stdlib.h
void *malloc(size_t size);
malloc() gets enough memory for a variable of size size. If there
is enough memory, it returns a pointer to that memory. If there
is NOT enough memory, it returns NULL.
malloc() returns a void pointer so you must typecast the return value
to be something you can use.
malloc() expects a value of size_t which is defined as an unsigned
integer and is the return type of the sizeof() function. You should
typecast this value or use the sizeof function.
NOTE: Several of the examples in Foster use neither and they will
usually work ok. However, it is better (and more consistent)
to use the sizeof() as used in the example in the middle of
page 594.
void free(void *ptr);
free() returns the memory pointed to by ptr to the system. It does NOT
set that pointer to NULL. The pointer still has the address of
the memory but the memory is no longer reserved and may have been
reallocated for other use.
free() returns nothing
free() expects a void pointer so you should typecast this value
void *calloc(size_t nmemb, size_t size);
calloc() allocates space for an array of elements of size with nmemb
elements in it. The array is set so that all bits are 0.
*/
int main(void)
{
int value; /* memory automatically provided by system */
int *ptr = NULL; /* memory for holding the pointer is automatically provided
but there is no memory allocated for holding the integer
value that pointer should be pointing to */
ptr = (int *)malloc(sizeof(int));
if (ptr == NULL)
printf("\nError, no memory left - exit");
else
{
/** do rest of program **/
printf("\nEnter an integer ");
scanf("%d", ptr);
printf("\nYou entered %d", *ptr);
value = *ptr * 2;
printf("\nValue = %d\n", value);
}
free((void *) ptr); /* The memory allocated to hold an integer is returned
to the system; however, the variable ptr STILL has
the address of that old memory. Be careful to set
ptr to NULL after a free() so that you don't
accidentally try to access the returned memory.*/
ptr = NULL;
return (0);
}