"half free" 一块内存来缩小它安全吗?

Is it safe to "half free" a chunk of memory to shrink it?

有人告诉我,即使它是安全的,也绝对是不好的做法。我的问题是,这样做真的安全吗,还是完全未定义的行为?假设我已经分配了一个 100 字节的内存块,但我想将它缩小到 50。将 50 添加到指针并释放它是否安全?这是代码示例:

char *ptr = malloc(100);
//...
free(ptr+50);
//Presumably, since I freed the second half only, would that be equivalent to ptr = realloc(ptr, 50);?

这是cross-platform/undefined行为吗?这种缩内存的方法安全吗?

您只能将从 mallocrealloccalloc 返回的指针传递给 free。传递其他任何内容是 undefined behavior.

关于 free 函数的 C standard 第 7.22.3.3p2 节指出:

The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

这里正确的做法是分配一个新的内存块,使用 memcpy 复制字节,free 旧块。