Why C array has extra bytes at tail? [duplicate]

时光总嘲笑我的痴心妄想 提交于 2019-12-20 07:48:26

问题


I examine that C array maybe have some extra bytes at tail.

There are my code

int a = 5;
int test[] = {1,2,3,4};
int b = 5;

test[-1] = 11;
test[4] = 11;

cout << b << endl; // 11 
cout << a << endl; // 5

You can see the running result there

the value of b is changed through changing test[-1]'s value. But when I change test[4]'s value, the value of a doesn't change;

I use gdb to check their addresses, found that

In g++ 6.4.0, the address of a substract address of test[4] is 8 bytes
In clang++ 3.8.1, the address of a substract address of test[4] is 4 bytes

So, I am curious that why the array has some bytes at tail?

Thanks @Peter A.Schneider to explaining the question. It is surely a UB , But it is just a experimental code. This isn't a discuss for practical code.

generally,variables at the runtime stack are close together. b is close to test, but why 'a' is not close to 'test+3'. That's the key of the problem.


回答1:


test[-1] = 11;
test[4] = 11;

This is undefined behavior.(Meaning anything could have happened). In your case you changed the value of b because they are adjacent in the memory where they are allocated. But you shouldn't rely on it. Because this may blow up your program or results in erroneous code behavior most of the time.

The UB you have is because `Accessing an array index out of bound in undefined behavior."



来源:https://stackoverflow.com/questions/47737913/why-c-array-has-extra-bytes-at-tail

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!