[英]Pointer arithmetic and dynamic memory?
What does the following piece of code mean? 以下代码是什么意思?
int* pointer = malloc (sizeof(int) + 3);
pointer++;
The allocated piece of memory can't be broken down into chunks of sizeof(int)
. 分配的内存不能分解为
sizeof(int)
块。 So what happens when pointer is asked to jump to the next "block"? 那么当指针被要求跳转到下一个“块”时会发生什么? Is it defined?
它定义了吗?
The code is valid but maybe unusual without more context. 代码有效,但如果没有更多上下文,可能会有所不同
Line 1: The malloc
allocates 3 bytes larger than the size of an int
. 第1行:
malloc
分配比int
大小大3个字节。 This is valid. 这是有效的。
Line 2: The pointer++
is valid. 第2行:
pointer++
有效。 It's just an address. 这只是一个地址。
Further references to pointer
(eg addition or subtraction or comparison) are valid. 对
pointer
进一步引用(例如,加法或减法或比较)是有效的。 Dereferences (ie *pointer
) will result in undefined behaviour. 解引用(即
*pointer
)将导致未定义的行为。
Not that those 3 "extra" bytes are valid storage space and can be addressed with a char *
, for example. 并非这些3个“额外”字节是有效的存储空间,并且可以使用
char *
进行寻址。
pointer
can be used for pointer comparison (C standard allows pointers to be one element past the last one). pointer
可用于指针比较(C标准允许指针成为超过最后一个的一个元素)。 Read or write access is undefined. 未定义读取或写入访问权限。
*pointer
is 3 bytes of 0 and sizeof(int) - 3
bytes of undefined. *pointer
是3个字节的0和sizeof(int) - 3
个字节的未定义。 Which byte[s] (as related to significance in your int
) are undefined is platform dependent (on the system bytesex) so in terms of your C program, the whole thing might as well be undefined. 未定义哪个字节[s](与
int
重要性相关)是平台相关的(在系统bytesex上),因此就C程序而言,整个事情也可能是未定义的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.