Don’t Forget the Null

Don’t Forget the Null

A valid C string consists of an array of zero or more characters plus an additional null character. Thus, the shortest possible string must contain at least one character. Remember that the function strlen() returns the size of the string excluding the null terminator. Therefore, in the following code fragment:

   char arr[3] = "hi" ; // null appended automatically  n = strlen("hi"); // equals 2, not three

the value of n is 2 rather than 3. This can lead to the following bug:

   char * strduplicate(const char *s )  {    int n = strlen(s);    char * p = new char [n]; // oops, array's too short    strcpy(p, s); // undefined behavior }

The char array allocated on the free store is one char too short. Since strcpy() automatically appends a null character at the end of the p, it causes a buffer overflow?the final null is written to an out of bound element. Therefore, remember always to make room for the null character:

   int n = strlen(s) + 1; // OK
Share the Post:
data observability

Data Observability Explained

Data is the lifeblood of any successful business, as it is the driving force behind critical decision-making, insight generation, and strategic development. However, due to its intricate nature, ensuring the

Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular