This malloc shouldn't work

后端 未结 5 1786
爱一瞬间的悲伤
爱一瞬间的悲伤 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:10

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

    It's not "working"; your code invokes undefined behavior. "Undefined behavior" doesn't mean "your code will segfault." That would be defined behavior. UB means anything can happen.

    In this case, you're stomping on memory you don't own. That will sometimes segfault, but don't count on it. C has no notion of "segfaults", that comes from your OS.

提交回复
热议问题