DEV Community

Ujjawal Chaudhary
Ujjawal Chaudhary

Posted on

Day 5: C Strings: The Danger of the Null Terminator (\0)

In Python or Java, strings are objects. You don't worry about how they end.

In C, a string is just a lie. It's actually just a character array.

So how does the computer know where the string stops? It looks for a secret hidden character called the Null Terminator (\0).

  • If you forget space for this \0, functions like printf won't stop reading.
  • They will keep printing memory (garbage data, or even sensitive data) until they accidentally hit a 0 somewhere in your RAM.

This is the root cause of the famous Buffer Overflow vulnerability.

The Code

Here is the code demonstrating "Safe" vs "Unsafe" strings.



// Day 5: The most dangerous character in C

#include <stdio.h>

int main() {
    // 1. Safe String (Compiler adds \0 automatically)
    // Size is 6 bytes ('H', 'e', 'l', 'l', 'o', '\0')
    char safe[] = "Hello"; 

    // 2. Unsafe String (Manually built, NO null terminator)
    // Size is 2 bytes. 
    char unsafe[2] = {'H', 'i'}; 

    printf("Safe String: %s\n", safe);

    // DANGER: printf keeps reading memory until it finds a 0.
    // It will print "Hi" followed by random garbage from your RAM!
    printf("Unsafe String: %s\n", unsafe);

    return 0;
}

πŸ“‚ View the source code on GitHub: https://github.com/Ujjawal0711/30-Days
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
pauljlucas profile image
Paul J. Lucas

While such a program likely will print some garbage, it can alternatively simply crash due to a segmentation violation.

Also, reading past the end of an array generally is not called "buffer overflow" β€” that's an "out-of-bounds" error.

A "buffer overflow" is also an out-of-bounds error, but more specifically and only when you write past the end of an array β€” you overflow the buffer just as you can only overflow a glass of water by putting more water into the glass than it can handle.