Ask your own question, for FREE!
Computer Science 8 Online
OpenStudy (anonymous):

Can anyone explain to me how dynamically allocate memory in C language? I know about malloc, calloc, realloc & free. But I can't understand the implementation of them.

OpenStudy (rsmith6559):

malloc, if it succeeds, returns a pointer to a block of memory whose size you gave (in bytes) in the argument. If malloc can't get the memory, it returns NULL. You can assign the result of malloc() to a pointer of the correct data type.

OpenStudy (anonymous):

lets say you want to make a c-string but you don't know how the long the string should be so you make a pointer variable of type char to eventually point to a c-string you will point it to a block of memory specified by you to be large enough to hold the c-string ie.. char *p; /*creates a pointer of type char (this we can point to a c-string*/ int *p /* and int pointer if you wanted a pointer to an integer*/ lets say you want to store the string "Hello" that is 5 chars but for a c-string you will need to account for the null character at the end so you need room to hold 6 characters p = malloc(6 * sizeof(char)); /*points p to a memory block large enough to hold 6 characters.*/ you must test to make sure the memory allocation was successful before using the pointer if(p) /*if p != NULL (allocation successful)*/ strcpy(p, "Hello");/*copies Hello to block of memory pointed to by p and adds '\n' creating "Hello\n" now char pointer p points to a block of memory that holds the c-string "Hello\n" when youre done you free the memory free(p);/*releases the memory pointed to by pointer p*/ p = NULL/*after freeing memory so its not pointing to a block of memory any more*/ realloc is like malloc but it is used to reallocate a block of memory previously used ie.. you made p to point to a block of memory 6 chars long but want to make it long enough to hold "Hello World" you need 11 spaces for the string and 1 for null so 12 characters. p=realloc(NULL, (sizeof(char)* 12)); /*changes the memory block assigned by malloc to hold 12 characters*/ calloc is like malloc and realloc but the difference is calloc initializes the allocated memory block to zero when created.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!