0

Say, if I have this piece of code

void alloc_mem(int size, double **x) 
{


   *x = malloc(size*sizeof(double));

   for ( int i = 0; i < size; i++ ) ( *x )[i] = i;
}

void test_function()
{
    double *x;
    alloc_mem(10, &x);
    free(x);
}

I am allocating the memory on heap in one function, and deleting it inside another. Is it okay in

Poornima M
  • 11
  • 3

2 Answers2

2

Yes, this is valid and common. One of the reasons for using dynamic allocation is because the memory needs to be used outside of the function that allocates it -- if it only needed to be used locally, you might have been able to use a local variable. In this case, you'll necessarily have to free it in some other function.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

The idea is good, but a few more things are needed (or preferred).

Checks

Before malloc()

Before calling malloc, you should first check if size is valid (not negative number).

Also, although this shouldn't happen but if in alloc_mem, *x has already been allocated a piece of memory, and you assign a new memory to the pointer *x, it causes memory leak. It means part of your memory is not 'recycled' and is lost. It is very important that your program doesn't cause any memory leak because eventually your system will crash due to insufficient memory and reboot is the only way.

You can (one of the ways) first set the pointer you just declared (*x in test_function) to NULL. Then, in alloc_mem first check if the passed argument *x is NULL or not. If it is not NULL, you can just return to test_function, or free it and malloc a new memory to it. (Read the comment of this answer)

After malloc()

After malloc(), you should check if the returned address (in this case, *x) is a valid address. If your machine has run out of memory (very rare, but not impossible), you get a NULL pointer. If you didn't perform the check and continue the insertion / assignment, you will get a Segmentation Fault.


Conventions

Setting the pointer to NULL after freeing it

It is a good practice to set the pointer (x in test_function) to NULL after freeing it. You can get a detailed explanation here. It doesn't do much in your case but when you are working on a bigger project, it saves a lot of time debugging.

Check memory leaks

You can check if your program causes any memory leak by using valgrind. After installed, just use it like

$ gcc prog.c -o prog
$ valgrind ./prog

You should get something like

HEAP SUMMARY:
==4889==     in use at exit: 0 bytes in 0 blocks
==4889==   total heap usage: 1 allocs, 1 frees, 1,024 bytes allocated
==4889== 
==4889== All heap blocks were freed -- no leaks are possible
Henry Fung
  • 380
  • 3
  • 12