为什么这不会给出分段违规错误? [英] Why does this not give a segmentation violation fault?

查看:34
本文介绍了为什么这不会给出分段违规错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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;
}

我不明白为什么这没有给出分段错误,因为我有 2 个 int 的 malloc 空间,并且正在将 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 个 ints,并写入了 3 个 ints.

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屋!

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