我有点理解 realloc 的作用,但是当尝试重新分配一定大小的内存时,我似乎不明白。如果没有所需尺寸的连续尺寸怎么办?或者如果 null 作为指针传入,或者传入的大小为 0。我知道如果大小为 0,那么它想要释放该内存。 问题: 将 malloc 与 realloc 结合使用?
void *realloc(void *ptr, size_t newsize)
{
if(newsize == 0)
free(ptr);
if(ptr == NULL)
//does something
//how does it malloc a size and copy everything over?
}
最佳答案
if (newsize == 0) {
free(ptr);
return;
}
if (ptr == NULL)
return malloc(size);
// otherwise do a true realloc
至于
What if there is not a contigious size of the size wanted.
然后realloc
返回NULL
并设置errno
来指示错误。
关于c - 在 C 中使用 realloc 和 malloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16325629/