Question

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); // :)
Was it helpful?

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.

OTHER TIPS

  1. 'strcpy' function copies data from source to destination address including with '\0' termination character . 'strncpy' function copies data as the same way but if there is no termination character '\0' exists in the first n bytes to be copied, termination character will not be copied then and you will need to add it by yourself to terminate the string.

  2. You will always have to statically or dynamically allocate a memory space to play with. Therefore, you should declare a character array or dynamically allocate a chunk of memory first then you can play nice with your strings

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top