c中的堆内存

Heap memory in c

你能在 C 中调整数组的大小而不丢失以前大小的数组的数据吗?

malloc() 将您的数据放入堆内存中,但每次调用 malloc() 时,它都会选择堆内存中的不同位置作为起始位置

在一般情况下,这并不总是可行的,因为该内存位置可能没有扩展空间。有一个名为 realloc 的 CRT 函数,它可以就地扩展,或者分配新的缓冲区并将所有数据移动到那里。使用方法如下:

#include <stdio.h>
#include <stdlib.h>

int main() {
  void* p = malloc(10);
  if (!p) {
    puts("Failed to allocate 10 bytes.");
    return 0;
  }

  puts("Allocated 10 bytes");

  void* tmp = realloc(p, 15);

  if (!tmp) {
    puts("Failed to allocate more memory");
    free(p); // if allocation fails, you need to free the old buffer
    return 0;
  }

  puts("Allocated 15 bytes");

  if (tmp == p) {
    puts("Start pointer still same");
  }

  // if allocation succeeds with realloc, 
  // you only need to free the new buffer 
  // even if expansion was not in-place.
  free(tmp); 
}

参见documentation