-4

作为实践,我正在尝试重写 realloc 函数

void updateSize(void* p,int length)
{
    free(p);
    malloc(sizeof(p) * length);
}

int main(int argc,char* argv[])
{
    int *y =malloc(sizeof(int)*3);
    y = updateSize(y, 5);
}

但是当我尝试编译它时,我收到以下错误:

void value not ignored as it ought to be.

此错误的原因是什么,我该如何解决?

4

1 回答 1

1

OP 没有从函数返回值,也没有根据需要复制数据。

// Function return value of `void` needs to be `void *`.
// `length` should be of type size_t
// The former length of `p` needs to be passed.
// Potential NULL pointers need testing.
void updateSize(void* p,int length) {
  // Missing data copy.
  // Allocate new memory and copy before freeing old
  free(p);
  // Returned value from malloc needs saving.
  // No reason for 'sizeof()'
  malloc(sizeof(p) * length);
}

// Recommend
void *updateSize2(void* p, size_t OldLength, size_t NewLength) {
  void *p2 = malloc(NewLength);
  if (p && p2) {
    memcpy(p2, p, OldLength < NewLength ? OldLength : NewLength);
  }
  if (p2 || (NewLength == 0)) {
    free(p);  // Note A
  }
  return p2;
}

注意 A:当NewLength == 0. 一些malloc(0)实现返回 NULL,另一些则返回指向“无数据”的指针。在前者中,NULL 指针并不总是意味着失败malloc()。现在正如@sharth 正确指出的那样,free(p)应该只在内存分配失败时调用,if()这里使用的条件是NewLength.

于 2013-09-22T13:12:14.457 回答