Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Null-Termination and Its Importance | String Representation in C
Practice
Projects
Quizzes & Challenges
Вікторини
Challenges
/
C Strings

bookNull-Termination and Its Importance

Свайпніть щоб показати меню

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

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 1. Розділ 4

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Секція 1. Розділ 4
some-alt