malloc()和free()的使用问题

Questions on use of malloc() and free()

感谢您注意到我的问题。

在C Primer Plus中,它首先写

The argument to free() should be a pointer to a block of memory allocated by malloc(); you can’t use free() to free memory allocated by other means

这意味着一个 malloc(),一个 只有 free().

但后来就没了

It’s okay to use a different pointer variable with free() than with malloc(); what must agree are the addresses stored in the pointers.

这似乎与第一个陈述相矛盾。

所以我的理解是,只要一对malloc()free()共享同一个地址就没有错误,指针的名字也无所谓。我说得对吗?

变量包含一些值,可以是指针(即内存地址)。

两个变量可以包含相同的指针(即相同的地址),称为指针别名。

free 重要的是获取 malloc 先前给出的指针的 (即先前由 malloc)

例如:

void* p = malloc (100);
void* q = p;
free (q);

...很好。 free () 的参数是 malloc 返回的值。句子

"It’s okay to use a different pointer variable with free() than with malloc()"

实际上毫无意义,只会造成混乱——当然,只要值相同,使用不同的变量就可以了。

请记住,释放任何别名会使所有指针无效

int *a, *b, *c, *d, *e;
a = malloc(42 * sizeof (int));
b = a;
c = b;
d = c;
e = d;
a[0] = 42;
b[1] = 100; // same as a[1]
c[2] = 999; // same as a[2]
d[3] = -1;  // same as a[3]
e[4] = 0;   // same as a[4]
free(d); // for example
// all of a, b, c, d, and e are now invalid;