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

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

问题描述

Example code:

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

  return 0;
}

See in code I have done some invalid reads and invalid writes, but this small program works fine and does not create a core dump.

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

Question:

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

解决方案

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 ("
size: %d
", sizeof b); 
    printf ("
c: %s
", c); 
    return 0;
}

Sample output:

$ ./a.out 

size: 12

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

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天全站免登陆