Search code examples
cstringmallocstrcpystrncpy

How to robustly copy text to char* without any errors


I have 2 questions..

  1. is it necessary to add a termination character when executing the following commands against a char *string ?

    strcpy();

    strncpy();

  2. Is it necessary to allocate memory before before doing any operation with the above to function against the char *string ?

for example..

char *str;
str = malloc(strlen(texttocopy));
strcpy(texttocopy, str); // see the below edit

Please explain.

EDIT : in the above code I inverted the argument. it is just typo i made while asking the question here. The correct way should be

strcpy(str, texttocopy); // :)

Solution

  • The strcpy function always adds the terminator, but strncpy may not do it in some cases.

    And for the second question, yes you need to make sure there is enough memory allocated for the destination. In your example you have not allocated enough memory, and will have a buffer overflow. Remember that strlen returns the length of the string without counting the terminator. You also have inverted the arguments to strcpy, the destination is the first argument.