This malloc shouldn't work

后端 未结 5 1788
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-23 17:06

Here is my code.

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

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

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

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


        
5条回答
  •  -上瘾入骨i
    2021-01-23 17:57

    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.

    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]));
    }
    

    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.

提交回复
热议问题