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
.