1

I know that in language like c I need to free the memory after I allocate it. ( I am coming from java), regarding this I have a couple of questions:

  1. when I am doing:

    int array[30];      
    

    (i.e creating an array of size 30 integers) is this the same as doing?

    int array[] = malloc(sizeof(int)*30);
    
  2. As a sequence to the first question, when I create array(s) inside a function (i.e local to the function and not global to the whole file), do I need to free the memory for this array inside the function where I create it? (I don't see any other way to free it since I can't pass a reference of all arrays created back to the main() function).

So in short, i want to know exactly when do I need to free memory for objects/primitives created (in or outside of a function).

Krishnabhadra
  • 34,169
  • 30
  • 118
  • 167
user2030118
  • 155
  • 3
  • 14

5 Answers5

6

If you say

int array[30];

this is on the stack and will automatically get cleaned up for you when it goes out of scope.

If you say

int * array = (int *)malloc(sizeof(int)*30);

the memory will be allocated on the free store (heap), and you are in charge of freeing it

free(array);

The same applies whether the code is, be that inside a function call, or in main. If you use malloc, you need to use free.

doctorlove
  • 18,872
  • 2
  • 46
  • 62
5

No, it's not the same at all.

The first one reserves memory using "automatic allocation", which is generally on the stack. This memory will be automatically de-allocated once the object goes out of scope, as in when the function returns for instance.

The second one uses malloc() to allocate memory "on the heap"; this memory must be de-allocated using free() when no longer needed.

Also, the proper syntax is:

int *array = malloc(30 * sizeof *int);

You can't use [] like that in C.

unwind
  • 391,730
  • 64
  • 469
  • 606
0

If you use int array[30], you allocate the array on the stack and it lives only in the scope it was created in. If you use malloc, the memory must be released manually with free.

Both approaches are different, and serve different needs. Stack-allocated variables/objects have a limited scope whereas you can use malloc'd objects beyond the local scope.

Use malloc with pointers, though:

int *array = malloc(sizeof(int)*30);
bash.d
  • 13,029
  • 3
  • 29
  • 42
Michael M.
  • 2,556
  • 1
  • 16
  • 26
0

Your array int array[30] will be put on the stack and its allocates memory will automatically be released, once array goes out of scope. But, when you allocate memory using malloc/calloc/realloc you need to explicitly free this memory.

bash.d
  • 13,029
  • 3
  • 29
  • 42
0

Basically malloc allocates memory in the heap and does not get freed after losing scope. So memory allocated using malloc should be freed using free.

Sakthi Kumar
  • 3,047
  • 15
  • 28