This malloc shouldn't work

后端 未结 5 1790
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  北荒
    北荒 (楼主)
    2021-01-23 18:04

    it's seems like this: malloc allocates some bytes more than you specify..

    when you use malloc(sizeof(s)*2); //8 then while (i <= 36) is ok, but while (i <= 37) already not..

    when you use e.g malloc(sizeof(s)*4); //16 then while (i <= 7572) is ok, but while (i <= 7573) already not..

    (I tested in code::blocks)

    Too bad that Dennis Ritchie is dead, it's still big mystery why it's like that, but just don' worry about it too much just allocate always enough you need and null terminate strings too

提交回复
热议问题