This malloc shouldn't work

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

    Segfault is a signal from the OS telling you that accessing a particular memory zone is none of your business. It just so happens that what you're accessing doesn't trigger alarms from the OS's memory management unit. There are tons of ways to exploit that (overriding function calls, attacks on binaries by overwriting stack values etc).

    It may also be the case that your malloc doesn't allocate those 2 bytes and 2 bytes only. Malloc invokes a system call that allocates virtual memory pages (which are likely way more than 2 bytes). That syscall (sbrk and VirtualAlloc for Linux and Windows, respectively) tells the OS to map those pages onto what you need, then protect them so that nobody else (read: another process/application) accidentally treads on your memory zone ('cause in that case the OS would hit that one's head with a segfault).

    And there's also the undefined behavior thing the others mentioned.

提交回复
热议问题