Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct free() of string array C

This may be a newbie fault, but I am greatful for any tips on what exactly I do wrong.

The code:

int main()
{
  int i =0;
  char ** nameslist;
  nameslist = malloc(5 * sizeof(char*));

  for (i=0; i <5; i++)
  {
      nameslist[i]=malloc((20+1)*sizeof(char));
  }

  nameslist[0]="John";
  nameslist[1]="Adam";
  nameslist[2]="Nick";
  nameslist[3]="Joe";
  nameslist[4]="Peter";

  for (i=0; i <5; i++)
  {
    free(nameslist[i]);
  }

  free(nameslist);
  return 0;
}

Using Valgrind, I still see that I have memory leaks in heap - how do I fix this issue? I suspect that I malloc too much space - but still, how do I go about freeing space I don't necesarrily use?

Thankful for any hints!

like image 359
Pavoo Avatar asked Mar 12 '14 17:03

Pavoo


People also ask

Do I have to free a string in C?

yes, you need to free the memory returned by malloc.

Do you need 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.

What is C string array?

The string is a collection of characters, an array of a string is an array of arrays of characters. Each string is terminated with a null character. An array of a string is one of the most common applications of two-dimensional arrays.

Does free return anything in C?

free() doesn't return anything. It doesn't need to. Show activity on this post. malloc returns a pointer ( void* ) to the allocated memory.


2 Answers

The problem is that when you write this:

nameslist[0]="John";

You're not actually using the memory you have allocated. "John" is itself a pointer and you're overwriting the adress returned by malloc with this new pointer.

Use the strncpy() function to copy the string into the memory you allocated.

like image 58
Kaidjin Avatar answered Oct 21 '22 10:10

Kaidjin


Your malloc and free stuff is fine, but you are orphaning the original string when you try to do assignment like this:

nameslist[0]="John";

Instead you should use strcpy:

strcpy(nameslist[0], "John");
like image 35
Paul R Avatar answered Oct 21 '22 09:10

Paul R