devxlogo

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
See also  5 Tips to Manage a Remote Workforce
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist