Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to free memory from char array in C

Tags:

c

I created a char array like so:

char arr[3] = "bo"; 

How do I free the memory associated with array I named "arr"?

like image 475
AbhishekSaha Avatar asked Feb 02 '14 17:02

AbhishekSaha


People also ask

How do you free memory in an array?

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.

What is free () in C?

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.

Do you have to free an array in C?

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.


1 Answers

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

like image 99
rullof Avatar answered Oct 14 '22 04:10

rullof