Question Details

No question body available.

Tags

c string pointers memory-management malloc

Answers (2)

Accepted Answer Available
Accepted Answer
June 24, 2026 Score: 10 Rep: 222,090 Quality: Expert Completeness: 100%

Things like this is a recurring FAQ among beginner C programmers. They do something wrong and expect a deterministic outcome like an error message. But C is only deterministic when you do things right. When you do things wrong and end up invoking undefined behavior, then anything can happen - including the program seeming to work OK for now.

Compilers are only obliged to message you when your code violates syntax or core language rules - constraints, in all other situations it doesn't have to message you. And most forms of undefined behavior are run-time problems so there might be no way for the compiler to detect them even.

Why did it work this time?

  • Maybe there was some heap memory in the region you wrote to that nobody is missing, this time, and therefore it worked.
  • Maybe there was some heap memory in the region you wrote to that was really important to your program, and now you've trashed that memory, but at least you can print "hello world" just fine.
  • Maybe the compiler optimized away the whole thing and replaced your whole program with the equivalent of puts("hello world").
  • Or something else.

More details here: What is undefined behavior and how does it work?

As for how to avoid - if you use a modern version of gcc, it got a built-in dynamic analyzer invoked by -fsanitize. Compiling your code with -fsanitize=address gives additional info about a spotted heap buffer overflow, like this:

==1==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x745b11de0011 at pc 0x783b1343eb44 bp 0x7ffc98f9f760 sp 0x7ffc98f9ef20 WRITE of size 13 at 0x745b11de0011 thread T0 #0 0x783b1343eb43 in memcpy (/opt/compiler-explorer/gcc-16.1.0/lib64/libasan.so.8+0x129b43) (BuildId: c1ce38ce5c88b82634d528001926b27404a36d26) #1 0x0000004010cf in main /app/example.c:8 #2 0x783b1302a1c9 (/lib/x8664-linux-gnu/libc.so.6+0x2a1c9) (BuildId: 8e9fd827446c24067541ac5390e6f527fb5947bb) #3 0x783b1302a28a in libcstartmain (/lib/x8664-linux-gnu/libc.so.6+0x2a28a) (BuildId: 8e9fd827446c24067541ac5390e6f527fb5947bb) #4 0x000000401144 in _start (/app/output.s+0x401144) (BuildId: e88056f2bbba54c59020b83edfbea86660ac42d5)
June 24, 2026 Score: 4 Rep: 2,405 Quality: Low Completeness: 40%

It doesn't. You just wrote past the allocated memory and just entered the domain of undefined behaviour, and this is a typical example that can lead to software being remote exploitable. Imagine your buffer p being a buffer filled up with data from a network connection.

If you are on a Linux or BSD system, try to run your example using valgrind, a memory validator tool:

valgrind ./my-compiled-program