5

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!

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 Calling free on the constants is probably not a great idea either, which this fixes too.
6

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.