【问题标题】:use malloc for double pointer in C90在 C90 中使用 malloc 作为双指针
【发布时间】:2018-04-08 18:06:41
【问题描述】:

我正在尝试创建一个结构数组,但一开始我不知道它的大小。

struct MyStruct** thing;
size_t thing_len = 0;
thing = (struct MyStruct**) malloc(thing_len * sizeof(struct MyStruct*));
//...
thing_len += 1
thing = (struct MyStruct**) realloc(thing_len * sizeof(struct MyStruct*));

当我这样做时,thing 得到类型 MyStruct* 而不是 MyStruct** 并包含 0x0。但是当我这样做时

struct MyStruct* thing;
size_t thing_len = 0;
thing = malloc(thing_len * sizeof(struct MyStruct));
//...
thing_len += 1
thing = realloc(thing_len * sizeof(struct MyStruct));

有效!!

我不知道它是否改变了某些东西,但我正在使用 -ansi-pedantic 选项。

【问题讨论】:

标签: c pointers struct realloc c89


【解决方案1】:

在您的代码中

  realloc(thing_len * sizeof(struct MyStruct*));

是对函数的错误调用。您必须使用格式[检查man page]

 realloc(<old pointer>, new size);

也就是说,像这样的格式

 oldPointer = realloc (oldPointer, newSize);

是一段非常危险的代码。如果realloc() 失败,你最终也会丢失原来的指针!!

使用realloc()的规定方式是

 tempPointer = realloc (oldPointer, newSize);  //store the return
 if (tempPointer)                              // is it success?
 {
        oldPointer = tempPointer;              // cool, put it back to the variable you want
 }
             //--> here, whether or not realloc is success, you still got a _valid_ pointer.

【讨论】:

  • 在许多情况下,如果realloc() 失败,程序将注定要惨死。包含一个显式的if (!oldPointer) out_of_memory_error() 可能比死于 SIGSEGV 更好,但是在代码无论如何都会死的情况下保留旧指针的副本并不一定有帮助。可惜没有“malloc_or_die”、“realloc_or_die”等的标准函数,因为它们可以消除对大量冗余错误处理代码的需要。
猜你喜欢
  • 1970-01-01
  • 2017-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多