I created a char array like so:
char arr[3] = "bo";
How do I free the memory associated with array I named "arr"?
How do I free the memory associated with array I named "arr"? You should declare this as char arr[] = "bo" to allow the compiler to work out the length and so make sure that there is enough room for a null terminator. If you changed your code to char arr[3] = "boo"; then there would be no null terminator.
C library function - free() The C library function void free(void *ptr) deallocates the memory previously allocated by a call to calloc, malloc, or realloc.
no, you must not free such an array. There's a reason non-static local variables are said to have automatic storage duration… Also, forget about "the stack" and "the heap". The C standard only specifies abstract semantics for automatic, static and dynamic storage duration.
Local variables are automatically freed when the function ends, you don't need to free them by yourself. You only free dynamically allocated memory (e.g using malloc
) as it's allocated on the heap:
char *arr = malloc(3 * sizeof(char)); strcpy(arr, "bo"); // ... free(arr);
More about dynamic memory allocation: http://en.wikipedia.org/wiki/C_dynamic_memory_allocation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With