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
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.