gpt4 book ai didi

c - C中任意内存的类型

转载 作者:太空宇宙 更新时间:2023-11-04 01:22:24 24 4
gpt4 key购买 nike

这是关于这个问题的引用

How to implement the c malloc/realloc functions properly?

接受的答案提到 char 数组可用于为任意内存池建模。

然而,对该已接受答案的评论之一是

A char array that doesn't have allocated storage duration can only be aliased by a character type. In other words it cannot and it should not be used as arbitrary memory

这是正确的吗?如果是这样,那么可以使用什么?我想避免使用 alloc 或任何特定的操作系统调用 - 所以我对这个问题持对称态度。

最佳答案

周围有不同的问题。首先如@Magisch 的 answer 所示相关问题是返回一个悬挂指针,导致未定义的行为和通常的执行错误。

第二个与@^*#(此处审查)严格的别名规则有关。当您将字符数组用作大缓冲区以从中分配任何类型时,只要您确保正确对齐,普通编译器就会生成正确的代码。毕竟,这是他们实现 mallocreallocfree 例程的方式。由于它们是托管环境(C 标准库)的一部分,编译器开发人员还没有受虐狂到足以禁止这种用法。

但是 C 标准在这里更严格一些。你应该阅读我自己的回答 here对于类似的问题,特别是@EOF 的评论:

You cannot parcel of parts of an object declared as char [] into objects of other types (except character types), because they do have a declared type... which means technically you can't implement malloc() in pure C

关于c - C中任意内存的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38968296/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com