为什么这不给分段违例的错吗? [英] Why does this not give a segmentation violation fault?
问题描述
#include <stdio.h>
#include <stdlib.h>
int noOfIntegers = 2;
struct stack {
int *s;
int top;
} st;
void push(int item) {
st.top++;
st.s[top] = item;
}
int main() {
st.s = malloc (2 * (sizeof(int)));
st.top = -1;
push(1);
push(2);
push(3);
return 0;
}
我不明白这是为什么不给分段错误,因为我已经malloc分配空间2 INT
的,而且我插入3到数组由指针指向。
I don't understand why this is not giving a segmentation fault, as I have malloc'd space for 2 int
's, and am inserting 3 into the array pointed to by the pointer.
推荐答案
的malloc
分配从堆内存空间;你已经在堆中分配2 整数
,并写出3 整数
。结果
malloc
allocates space from the heap memory; you have allocated 2 ints
on the Heap, and write 3 ints
.
你的程序存储器通常在中等大小的块分配给对内存管理更有效。
Memory for your program is typically allocated in moderately sized chunks to be more efficient for the memory manager.
请求1字节?你可能有8个字节。结果
请求7个字节?你可能有8个字节。结果
要求14个字节?你可能有16个字节。结果
的(或者至少其16字节...)的
Request 1 byte? You probably got 8 bytes.
Request 7 bytes? You probably got 8 bytes.
Request 14 bytes? You probably got 16 bytes.
(or maybe its 16-bytes at a minimum...)
您只的保证的访问您实际要求的内存,但你有时可以编写超出了几个字节,而不会引起问题。只是有没有答应,过多的写操作是安全的。您的可能的获得赛格故障,则可能不会!
You are only guaranteed access to the memory you actually requested, but you can sometimes write beyond that for a few bytes without causing a problem. There's just no promise that excessive writes will be safe. You might get a seg-fault, you might not!
这篇关于为什么这不给分段违例的错吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!