无效的读/写有时会造成分段错误,有时不 [英] Invalid read/write sometimes creates segmentation fault and sometimes does not

查看:123
本文介绍了无效的读/写有时会造成分段错误,有时不的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例code:

int main ()
{
  char b[] = {"abcd"};
  char *c = NULL;
  printf("\nsize: %d\n",sizeof(b));
  c = (char *)malloc(sizeof(char) * 3);
  memcpy(c,b,10);   // here invalid read and invalid write
  printf("\nb: %s\n",b);
  printf("\nc: %s\n",c);

  return 0;
}

见code我做了一些无效的读取和写入无效,但这个小程序工作正常,并不会创建一个核心转储

但是,一旦我很大的图书馆,每当我做无效的读取或写入无效的1个字节,它总是创建核心转储。

But once in my big library, whenever I make 1 byte of invalid read or invalid write, it was always creating core dump.

问:

为什么我有时一个无效的读/写得到一个核心转储,有时甚至没有得到一个核心转储?

Why do I sometimes get a core dump from an invalid read/write and sometimes do not get a core dump?

推荐答案

你正在尝试做的基本上是缓冲区溢出和放大器;您code样品中更具体堆溢出。你看到的崩溃只在时间的原因取决于你正在访问&放哪个存储区;如果还是不您有权限访问/写(已经由Dan Fego得到很好的解释)。我认为丹Fego提供的例子更多的是堆栈溢出(校正欢迎!)。 GCC具有堆栈(堆栈溢出)缓冲区溢出相关的保护。您可以在下面的例子中看到这个(堆栈溢出基础):

What you are trying to do is basically buffer overflow & in your code sample more specifically heap overflow. The reason you see the crash only at times depends on which memory area you are accessing & if or not you have permission to access/write it (which has been well explained by Dan Fego). I think the example provided by Dan Fego is more about stack overflow (correction welcome!). gcc has protection related to buffer overflow on the stack (stack smashing). You can see this (stack based overflow) in the following example:

#include <stdio.h>
#include <string.h>

int main (void)
{
    char b[] = { "abcdefghijk"};
    char c [8];
    memcpy (c, b, sizeof c + 1);      // here invalid read and invalid write
    printf ("\nsize: %d\n", sizeof b); 
    printf ("\nc: %s\n", c); 
    return 0;
}

示例输出:

$ ./a.out 

size: 12

c: abcdefghi���
*** stack smashing detected ***: ./a.out terminated

这保护可以通过禁用 -fno-堆栈保护在gcc的选项。结果
缓冲区溢出是安全漏洞的重要原因之一。不幸的是功能类似于的memcpy 不检查这类问题,但也有方式来防止这类问题。结果
希望这有助于!

This protection can be disabled using -fno-stack-protector option in gcc.
Buffer overflow are one of major cause of security vulnerability. Unfortunately function like memcpy do not check for these kinds of problems, but there are ways to protect against these kinds of problems.
Hope this helps!

这篇关于无效的读/写有时会造成分段错误,有时不的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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