Mind-blowing: String length calculation in C
Nikhil Vikraman
Posted on September 23, 2024
Introduction
In Javascript, we can get the length of a string by using the length() function. That's not the case when it comes to C.
In Javascript, strings are treated as objects. Whereas, strings in C are an array of characters. There is some stuff going on behind C as to why it is an array of characters.
In Javascript, JavaScript automatically manages memory for strings. When you create or modify a string, JavaScript’s garbage collector handles allocation and deallocation behind the scenes. In C, you need to manually manage memory for strings, especially when dynamically allocating memory with malloc(). You need to ensure the buffer is large enough to hold the characters and the null terminator, and you have to free the memory when it's no longer needed.
Enough with the comparison and stuff. Lets go to the main topic.
Explanation
In C, the compiler automatically adds a null terminator \0
after the end of a string, so that it can know that it reached the end of a string. Because:
Strings in C are not objects: Unlike languages like Python or Java, C doesn’t have a dedicated string type. Strings are just arrays of characters, and arrays in C don’t carry any information about their length. Hence, C needs a way to know where the string ends.
The null terminator marks the end: The null terminator (
\0
, which is the value 0 in ASCII) tells functions likestrlen()
,printf()
, and others that the string ends at this point, and they should stop reading the array. Without this, the function would continue reading adjacent memory, leading to unpredictable results or a crash.
So, if you’re manually creating or modifying character arrays, you must ensure to include the null terminator yourself. For instance, if you’re copying strings or building them character by character, you should explicitly add '\0' at the end.
['H', 'e', 'l', 'l', 'o', '\0']
Without the null terminator, C functions that operate on strings (like strlen()
, strcpy()
, etc.) would not know where the string ends. They would continue accessing memory beyond the intended string, potentially leading to crashes, memory corruption, or security vulnerabilities.
If you feel like this article helped you gather a bit of information, please extend your support by following me 😎
Follow me:
Posted on September 23, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024