Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Null-Termination and Its Importance | String Representation in C
Practice
Projects
Quizzes & Challenges
Quizer
Challenges
/
C Strings

bookNull-Termination and Its Importance

Sveip for å vise menyen

When you work with strings in C, you are actually dealing with arrays of characters. However, unlike some other languages, C does not store the length of a string alongside the data. Instead, C uses a special character called the null-terminator—represented as \0—to mark the end of a string. This means that every valid C string must end with a null-terminator so that functions and loops can recognize where the string finishes. Without this character, there is no way for C to know the boundary of the string, which can lead to serious problems.

main.c

main.c

copy
1234567891011
#include <stdio.h> int main() { char with_null[] = {'H', 'e', 'l', 'l', 'o', '\0'}; char without_null[] = {'H', 'e', 'l', 'l', 'o'}; printf("With null-termination: %s\n", with_null); printf("Without null-termination: %s\n", without_null); return 0; }

When you print the with_null array, the output is "Hello", as expected. This is because the string is properly terminated with \0, so printf knows where to stop. However, when you print without_null, the output is unpredictable. Since there is no null-terminator, printf keeps reading memory past the array until it accidentally finds a \0 somewhere, which can result in extra characters, garbage values, or even a program crash. This illustrates the danger of omitting the null-terminator: it leads to undefined behavior that can cause bugs or security vulnerabilities.

main.c

main.c

copy
1234567891011
#include <stdio.h> int main() { char greeting[] = "Hi!"; int i = 0; while (greeting[i] != '\0') { printf("%c ", greeting[i]); i++; } return 0; }

Many standard string functions in C, such as strlen, strcpy, and printf with the %s format specifier, depend on the presence of the null-terminator to know where the string ends. If the null-terminator is missing, these functions cannot operate safely, and the results are unpredictable. Always ensure that any character array meant to represent a string is properly null-terminated. This is fundamental for safe string handling in C.

question mark

What happens if a string in C is missing the null-terminator?

Select the correct answer

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 1. Kapittel 4

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Seksjon 1. Kapittel 4
some-alt