dcsimg
Login | Register   
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Language: C++
Expertise: Beginner
Apr 4, 2000

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


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
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date