在 C 中使用 free 释放非字符指针
Using free to deallocate a non char pointer in C
在阅读这篇文章时 article,我看到了这一段:
Pointers to objects may have the same size but different formats. This
is illustrated by the code below:
int *p = (int *) malloc(...); ... free(p);
This code may malfunction in architectures where int * and char * have
different representations because free expects a pointer of the latter
type.
这不是我第一次读到 free
需要 char*
类型。
我的问题是,如何释放p
?
注意:You should not cast the return value of malloc
in C.
这个问题说明了读取可能无效资源的危险。确保您阅读的资源准确无误极其重要!有问题的 OPs 资源,在它的时代并没有错,但是已经过时,因此,是无效。具有讽刺意味的是,K&R 2E 比 大一岁,但仍然非常符合日期(因此仍然强烈推荐),因为它遵循标准。
如果我们参考a more reputable resource (the free
manual),我们可以看到free
实际上期望指针是void *
类型:
void free(void *ptr);
... 就其价值而言,here's the malloc
manual showing that malloc
returns void *
:
void *malloc(size_t size);
在这两种情况下,如 C11/6.3.2.3p1(C11 标准)所述:
A pointer to void may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.
int *p = malloc(...); // A conversion occurs here; `void *` as returned by malloc is converted to `int *`
free(p); // ... and the reverse of the conversion occurs here, to complete the cycle mentioned in C11/6.3.2.3p1
注意(以防您第一次错过):You should not cast the return value of malloc
in C。毕竟,传递给 free
时不需要强制转换,对吗?
在阅读这篇文章时 article,我看到了这一段:
Pointers to objects may have the same size but different formats. This is illustrated by the code below:
int *p = (int *) malloc(...); ... free(p);
This code may malfunction in architectures where int * and char * have different representations because free expects a pointer of the latter type.
这不是我第一次读到 free
需要 char*
类型。
我的问题是,如何释放p
?
注意:You should not cast the return value of malloc
in C.
这个问题说明了读取可能无效资源的危险。确保您阅读的资源准确无误极其重要!有问题的 OPs 资源,在它的时代并没有错,但是已经过时,因此,是无效。具有讽刺意味的是,K&R 2E 比 大一岁,但仍然非常符合日期(因此仍然强烈推荐),因为它遵循标准。
如果我们参考a more reputable resource (the free
manual),我们可以看到free
实际上期望指针是void *
类型:
void free(void *ptr);
... 就其价值而言,here's the malloc
manual showing that malloc
returns void *
:
void *malloc(size_t size);
在这两种情况下,如 C11/6.3.2.3p1(C11 标准)所述:
A pointer to void may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.
int *p = malloc(...); // A conversion occurs here; `void *` as returned by malloc is converted to `int *`
free(p); // ... and the reverse of the conversion occurs here, to complete the cycle mentioned in C11/6.3.2.3p1
注意(以防您第一次错过):You should not cast the return value of malloc
in C。毕竟,传递给 free
时不需要强制转换,对吗?