1.11 - heap management
Posted: Wed Nov 05, 2008 9:40 am
1.11 - heap management
this section i will tell you about the functions C provide for memory allocation. all of the return the void* pointer that is typeless.
1.11.1 - allocation
there are 2 primarty functions malloc() and calloc(). both functions return a void*:
both functions return a pointer to a contiguous block of memory, or NULL if there was not enough memory available.
- malloc() gets a block of size requestedSize
- calloc() gets a block of size requestedSize*requestedCount and initializes this block to 0
if you have a pointer of type T* (just generic for my examlple)
you would use:
this is portable, also you should allways check to see if your call was successful.
note that i use an explicit cast when i use malloc and calloc and it looks like this.
my time is running out, but i'll do a quick example.
now we have a pointer p* that has space for 3 integers.
there are many ways to store and get information
will work fine.
to be continued...
1.11.2 Memory Deallocation
note i do not always do this which is bad. but its good practice to allways deallocate memory once you have completed the task. especially if it is a big program.
if you dont deallocate it that memory can be used again.
this section i will tell you about the functions C provide for memory allocation. all of the return the void* pointer that is typeless.
1.11.1 - allocation
there are 2 primarty functions malloc() and calloc(). both functions return a void*:
Code: Select all
void *malloc(size_t requestedSize);
void *calloc(size_t requestedCount, size_t requestedSize);
- malloc() gets a block of size requestedSize
- calloc() gets a block of size requestedSize*requestedCount and initializes this block to 0
if you have a pointer of type T* (just generic for my examlple)
Code: Select all
T *p;
Code: Select all
p = malloc(sizeof(T));
p = calloc(1, sizeof(T));
Code: Select all
int *p;
if((p = malloc(sizeof(int))) == NULL)
exit(EXIT_FAILURE);
*p = 12;
note that i use an explicit cast when i use malloc and calloc and it looks like this.
Code: Select all
p = (int*)malloc(sizeof(int));
Code: Select all
#define SIZE 3;
int *p;
if((p = (int*)malloc(SIZE * sizeof(int))) == NULL)
exit(EXIT_FAILURE);
there are many ways to store and get information
Code: Select all
p[0] = 10;
p[1] = 11;
p[2] = 12;
to be continued...
1.11.2 Memory Deallocation
note i do not always do this which is bad. but its good practice to allways deallocate memory once you have completed the task. especially if it is a big program.
if you dont deallocate it that memory can be used again.
Code: Select all
int *p;
if((p = (int*)malloc(SIZE * sizeof(int))) == NULL)
exit(EXIT_FAILURE);
*p = 12;
free(p);