如果我在用 calloc 分配的内存之外设置一个值会发生什么? [英] What happens if I set a value outside of the memory allocated with calloc?

查看:24
本文介绍了如果我在用 calloc 分配的内存之外设置一个值会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下事项:

int* x = calloc(3,sizeof(int));
x[3] = 100;

位于函数内部.

当我编译和运行程序时没有出现错误,但是当我使用 valgrind 运行它时,我得到一个大小为 4 的无效写入".

I get no error when I compile and run the program, but when I run it with valgrind I get an "Invalid write of size 4".

我知道我访问的内存位置超出了我用 calloc 分配的内存位置,但我试图了解实际发生的情况.

I understand that I am accessing a memory place outside of what I have allocated with calloc, but I'm trying to understand what actually happens.

堆栈中的某些地址(?)是否仍然具有值 100?因为肯定有比我用 calloc 分配的内存更多的可用内存.valgrind 错误是否更像是嘿,您可能不是故意这样做的"?

Does some address in the stack(?) still have the value 100? Because there must certainly be more available memory than what I have allocated with calloc. Is the valgrind error more of a "Hey, you probably did not mean to do that"?

推荐答案

我知道我正在访问的内存位置超出了我使用 calloc 分配的内存位置,但我正在尝试了解实际发生的情况.

I understand that I am accessing a memory place outside of what I have allocated with calloc, but I'm trying to understand what actually happens.

实际发生的事情"没有明确定义;这完全取决于被覆盖的内容.只要您不覆盖任何重要的内容,您的代码就会看起来按预期运行.

"What actually happens" is not well-defined; it depends entirely on what gets overwritten. As long as you don't overwrite anything important, your code will appear to run as expected.

您最终可能会破坏动态分配的其他数据.你最终可能会破坏一些堆簿记.

You could wind up corrupting other data that was allocated dynamically. You could wind up corrupting some bit of heap bookkeeping.

该语言不会对数组访问强制执行任何类型的边界检查,因此如果您读取或写入数组的末尾,则无法保证会发生什么.

The language does not enforce any kind of bounds-checking on array accesses, so if you read or write past the end of the array, there are no guarantees on what will happen.

这篇关于如果我在用 calloc 分配的内存之外设置一个值会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆