0

我正在尝试将指向指针(char**)的指针传递给将初始化它的函数,然后将其传递给另一个将释放内存的函数,但是我在释放时遇到了段错误,这导致我相信我的分配出了问题。

Valgrind 报告在这条线上使用了未初始化的值。tmp[i] 指向 0x0。

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

这是代码(这只是测试代码)

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

和调用:

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

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

  return 0;
}

我已经玩了一段时间了,阅读了指针等,但是我无法解决这个问题。任何想法都非常感谢!

4

2 回答 2

1

您需要分配给*test,而不是从中分配。怎么样:

void 
alloc_strings(char ***test, int count) 
{
    char **tmp = malloc(count * sizeof *tmp);
    /*...*/
    *test = tmp;
}
于 2013-02-10T14:55:28.693 回答
0

在代码示例中,

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

*test应该有一些空间来存储char **当前未分配的指针。因此,如果示例是这样的

char** array[1];

alloc_strings(&array[0], 7);

我觉得代码会起作用。

于 2013-02-10T14:59:07.867 回答