为什么我没有拿到SIGSEGV? [英] Why don't I get SIGSEGV?

查看:201
本文介绍了为什么我没有拿到SIGSEGV?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想明白是怎么回事,更precisely我为什么不同时内存位置,而根据我的理解不分配写收到分段错误。

I would like to understand what is going on here, more precisely why I do NOT receive a segmentation fault while writing on a memory location, which according to my understanding is not allocated.

比方说,我想定义为int的二维数组( testptr )。一维( 4 )是静态分配(为阵),第二维( 2 ),动态(作为指针)。

Let's say I want to define a 2D array of int (testptr). One dimension (4) is allocated statically (as an "array"), the second dimension (2) dynamically (as a "pointer").

// First dimension 4 rows static
int *testptr[4];
for (i=0; i<4; i++)
    testptr[i] = calloc(2, sizeof(int));
// Second dimension 2 columns "dynamically" (in this example it is really just a constant)

现在我写的一些地点:

testptr[0][0] = 5;
testptr[1][0] = 6;
testptr[2][1] = 7;
testptr[3][1] = 7;

以上所有我希望能正常工作,因为他们是一个4×2阵列之内。

All the above I expect to work fine, as they are within a 4x2 "array".

现在我写不应该被分配一个位置:

Now I write to a location which should not be allocated:

testptr[2][3] = 8;

和确保我写了许多人:

for (i=0; i<1000; i++)
    testptr[3][i] = i;

在所有这些我得到一个分段错误,也没有其他的错误。

In none of these I get a segmentation fault nor other errors.


  1. 是不是正确的说,我们是在未分配的内存写?

  2. 难道只是我们没有收到错误的运气,因为这些未分配的内存位置不被其他变量/进程保留?

  3. 我们是否可以假设,这样做将导致程序的其他点?
  4. 问题(段错误)
  1. Is it correct to say that we are writing on unallocated memory?
  2. Is it just luck that we are not receiving an error, as those unallocated memory locations are not reserved by other variables/processes?
  3. Can we assume that doing this will cause problems (segfaults) in other points of the programs?

谢谢您的回答。

推荐答案

您程序调用的未定义行为即可。这将使无论是预期的或意外的结果。谁也不能保证在访问数组越界会产生分段错误,否则将要崩溃您的硬盘!

Your program invokes undefined behavior. It will give either expected or unexpected results. There is no guarantee that accessing arrays out of bounds will produce a segmentation fault or it will gonna crash your hard disk!

这篇关于为什么我没有拿到SIGSEGV?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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