How to free memory from char array in C
Asked Answered
D

4

42

I created a char array like so:

char arr[3] = "bo";

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

Delicacy answered 2/2, 2014 at 17:23 Comment(1)
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.Dispense
C
79

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

Clite answered 2/2, 2014 at 17:36 Comment(0)
P
15

You don't free anything at all. Since you never acquired any resources dynamically, there is nothing you have to, or even are allowed to, free.

(It's the same as when you say int n = 10;: There are no dynamic resources involved that you have to manage manually.)

Phototelegraph answered 2/2, 2014 at 17:24 Comment(0)
D
11

The memory associated with arr is freed automatically when arr goes out of scope. It is either a local variable, or allocated statically, but it is not dynamically allocated.

A simple rule for you to follow is that you must only every call free() on a pointer that was returned by a call to malloc, calloc or realloc.

Dispense answered 2/2, 2014 at 17:25 Comment(0)
R
1
char arr[3] = "bo";

The arr takes the memory into the stack segment. which will be automatically free, if arr goes out of scope.

Relique answered 11/9, 2019 at 15:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.