这个malloc不应该工作 [英] This malloc shouldn't work

查看:78
本文介绍了这个malloc不应该工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码.

 int     main()
  {
  char *s;
  int i = 0;

  printf("%lu \n", sizeof(s));

  s = malloc(sizeof(char) * 2);

  printf("%lu \n", sizeof(s));
  /*Why is this working?*/
  while (i <= 5)
    {
      s[i] = 'l';
      i++;
    }
  printf("%s \n", s);

  printf("%lu \n", sizeof(char));

  printf("%lu \n", sizeof(s[0]));
  }

在我看来,这应该是段错误,因为我尝试编写的内容超出了我的分配范围.为什么这样做有效?

In my opinion, this should segfault as I'm trying to write more than I allocated. Why is this working?

推荐答案

示例 (并完全同意)@Ed S的答案 ,请尝试在您的代码示例中添加一小部分附加变量,这些附加变量的声明方式完全相同,并在char *s之后进行malloc.

In illustration (and complete agreement with) @Ed S's answer, Try this example of your code with the small additions of an additional variable declared exactly the same way and malloc'ed right after the char *s.

尽管不能保证 将变量顺序存储在内存中,但以这种方式创建变量的可能性很高. 如果是,则char *t现在将拥有char *s将会占用的空间,并且您遇到段错误:

Although no guarantees that the variables are stored sequentially in memory, creating them this way makes it a high probability. If so, char *t will now own the space that char *s will encroach on, and you will get a seg fault:

int     main()
{
    char *s;
    char *t;//addition
    int i = 0;

    printf("%lu \n", sizeof(s));

    s = malloc(sizeof(char) * 2);
    t = malloc(sizeof(char) * 2);//addition

    printf("%lu \n", sizeof(s));
    /*Why is this working?*/
    while (i <= 5)
    {
      s[i] = 'l';
      i++;
    }
    printf("%s \n", s);

    printf("%lu \n", sizeof(char));

    printf("%lu \n", sizeof(s[0]));
}

注意: :在我使用的环境中(Windows 7,NI Run-Time,调试等),我都遇到了段错误,这在某种程度上支持其他答案中未定义的行为断言.

Note: In the environment I use, (Windows 7, NI Run-Time, debug, etc) I get a seg-fault either way, which somewhat supports the undefined behavior assertions in other answers.

这篇关于这个malloc不应该工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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