简体   繁体   English

malloc 接触未分配的内存

[英]malloc touching unallocated memory

I'm wondering why my allocation is working.我想知道为什么我的分配有效。 I created ptr which is a pointer and ptr2 which a pointer on the same location than ptr .我创建了ptr ,它是一个指针, ptr2是与ptr位于同一位置的指针。

Here's my code:这是我的代码:

int* ptr = malloc(sizeof(int));
int* ptr2 = ptr;
*ptr2 = 1;
ptr2 = ptr+1;
*ptr2 = 2;

At the end I've an array of two integer like that :最后,我有一个由两个整数组成的数组:

ptr[0] = 1
ptr[1] = 2

My question is : why I can affect the value 2 to ptr2 without error or warnings ?我的问题是:为什么我可以在没有错误或警告的情况下将值 2 影响到ptr2 I only malloc() -ed for one integer place in my array, isn't it?我只对数组中的一个整数位置进行了malloc() -ed,不是吗?

The problem here is, by saying这里的问题是,通过说

  ptr2 = ptr+1;

you're pointing to out of bound memory.你指的是内存溢出。 Next upon dererencing, you invoke undefined behavior .接下来在 deerencing 时,您调用undefined behavior Now, the outcome of UB cannot be justified, in any way.现在,无论如何都不能证明 UB 的结果是合理的。

There is nothing inherent in C that stops you from accessing out of bound (or invalid) memory, but the outcome of doing so is UB. C 中没有任何固有的东西可以阻止您访问越界(或无效)内存,但这样做的结果是 UB。

That said, just a suggestion, you should always check the returned value of malloc() before using that pointer to avoid UB by dereferencing NULL pointer, in case of malloc() failure.也就是说,只是一个建议,在使用该指针之前,您应该始终检查malloc()的返回值,以避免在malloc()失败的情况下通过取消引用NULL指针来避免 UB。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM