-
Notifications
You must be signed in to change notification settings - Fork 2
strcpy and strncpy
Wu Jie edited this page Mar 30, 2014
·
1 revision
strcpy(to,from) will copy the string including its null terminator(e.g. '\0'). strncpy(to,from,count) will copy the exactly count of character, it will not add null terminator(e.g. '\0') for you, so you have to manually check the destinate string.
Here are some example that show you the dangers, and help you know how to correct them.
Example 1: Correct! don't worry about null terminator, the strcpy will automatically add for you
char dest[128];
const char* src = "hello world";
strcpy( dest, src );Example 2: Wrong! strncpy never add null terminator for you.
char dest[128];
const char* src = "hello world";
memset(dest,1,128);
strncpy( dest, src, strlen(src) );
// dest[strlen(src)] = 0; // To correct it, you must add this line.Example 3: Wrong! strlen just count the character and exclude null terminator (e.g. '\0')
char* dest;
const char* src = "hello world";
dest = malloc(strlen(src));
// CORRECT: dest = malloc(strlen(src)+1);
strcpy( dest, src );