更改指针后,free() 将释放多少字节?

How many bytes will be deallocated with free() after changing the pointer?

我有以下代码。

char* p = malloc(10);
p = p + 1;
free(p);

在上面的代码中,

  1. malloc return调用malloc(10)时的内存地址是怎么得到的?
  2. 使用 free(p) 将释放多少字节?
  3. free()如何知道要释放多少字节?

free 的手册页会告诉您,除了从 malloc 返回的指针外,任何参数都具有未定义的行为:

The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed

关于 free 如何知道块的大小:典型的内存分配器实现对每个块(包含大小、空闲列表指针等)有一个 header 和 free知道这个 header 的大小和 malloc.

返回的指针的偏移量

这也回答了你的第一个问题:malloc 分配了这样一个块和 returns 指向实际 object.

开始的指针