Eddie
Eddie

Reputation: 13126

Allocating and Freeing pointer to pointer

I'm attempting to pass a pointer to a pointer (char**) into a function that will initialize it, and then pass it into another function that will free the memory, however I'm getting seg faults on the freeing which leads me to believe my allocation is going wrong.

Valgrind is reporting use of uninitalized value at this line. tmp[i] is pointing to 0x0.

if(tmp[i]) free((char*)tmp[i]);

Here is the code (this is only test code)

void 
alloc_strings(char ***test, int count) 
{
  char **tmp = *test;
  tmp = malloc(count * sizeof(char*));

  int i;
  for(i = 0; i < count; i++) {
    tmp[i] = malloc(6);
    strcpy(tmp[i],"Hello");
  }
}

void
free_strings(char ***test, int count)
{
  char **tmp = *test;

  int i;
  for(i = 0; i < count; i++) {
    if(tmp[i]) free((char*)tmp[i]);
  }

  if(tmp)
    free(tmp);
}

And the invocation:

int
main(int argc, char **argv)
{

  char **test;
  alloc_strings(&test, 10);
  free_strings(&test, 10);

  return 0;
}

I have been playing around with this for a while, reading up on pointers etc however can't get my head around the issue. Any thoughts greatly appreciated!

Upvotes: 0

Views: 93

Answers (2)

Ganesh
Ganesh

Reputation: 5990

In the code example,

alloc_strings(char ***test, int count) 
{
    char **tmp = *test;

*test should have some space to store a pointer to char ** which currently is not allocated. Hence, if the example is as this

char** array[1];

alloc_strings(&array[0], 7);

I feel that the code will work.

Upvotes: 0

cnicutar
cnicutar

Reputation: 182794

You need to assign to *test, not to assign from it. How about:

void 
alloc_strings(char ***test, int count) 
{
    char **tmp = malloc(count * sizeof *tmp);
    /*...*/
    *test = tmp;
}

Upvotes: 1

Related Questions