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);