Dynamic Memory Allocation consists of many areas, the most known is malloc which comes in a form of:
void *malloc(size_t size);
A simple malloc would be the following which will reserve 5 bytes to every ip.
int *ip;
ip = malloc(5 * sizeof(ip));
Pretty simplistic. sizeof(int) returns the sizeof an integer on the machine, multiply by 5 and malloc that many bytes. The second malloc works because it sends what ip is pointing to, which is an int.
You might say what if we run out of allocated memory during the run-time of our program and need to give more memory! Then we have a function called realloc which will give more memory for that pointer. Realloc comes in the form of:
void *realloc(void *ptr, size_t size);
Some person can quickly say lets just allocate some memory everytime we are empty. So you might have done this:
ip = realloc(ip, sizeof(ip) + sizeof(int)*5);
As every programmer knows... This is quite WRONG. If the realloc on ip fails? ip gets set to NULL, and the previously allocated memory to ip now has no pointer to it. Now we have allocated memory just floating in the heap without a pointer. This is called a memory leak.
Now a better way is to create a temporary pointer. If realloc fails, then it isn't a big problem as we keep our ip pointer on the original memory space.
int *tmp;
if ((tmp = realloc(ip, sizeof(int) * (INITIAL_ARRAY_SIZE + 5))) == NULL) {
// Possible free on ip?
fprintf(stderr, "ERROR: realloc failed");
}
ip = tmp;
As you see, the above function works as a charm! Becarefull when you use malloc and realloc since you can come with many exploits and code faults within your application from memory leakage and bufffer overflows.!
2006-07-02 09:57:19
·
answer #1
·
answered by ? 6
·
0⤊
0⤋
a wisdom shape is a team of archives factors grouped together below one call. those archives factors, standard as participants, could have categories and different lengths. the technique of allocating memory at run time is standard as dynamic memory allocation. inspite of the reality that c would not inherently have this facility there are 4 library workouts which permit this function. Many languages enable a programmer to specify an array length at run time. Such languages have the potential to calculate and assign in the process executions, the memory area required via the variables contained in this technique. yet c inherently would not have this facility yet helps with memory administration applications, which would be utilized to allocate and unfastened memory in the process this technique execution. right here applications are utilized in c for purpose of memory administration.
2016-11-01 01:57:24
·
answer #2
·
answered by mcthay 4
·
0⤊
0⤋