bml said:
char s1 = "this string";
char *s2;
s2 = (char *)malloc(30);
memset(s2, 0, 30);
/* this supposes to copy string s1 to s2 */
while((*s2++ = *s1++) != '\0');
/* Why empty content of s2 print out here*/
Empty ? I'm not sure. I would have said 'undeterminated', due to the lack of
final 0.
add :
*s2 = 0;
but you are making a design mistake. You have changed the value of s2, hence
you have lost it's initial value:
- The string copy was somehow correct, but you don't know any more where does
the copied string begin.
- You are now unable to free the allocated block which has created a memory
leak. (A Bad Thing (c))
If you want to make a copy of a string, I recommend to desing your own
'strdup()' function:
#include <string.h>
#include <stdlib.h>
char *str_dup (char const * const s)
{
char *sdup;
if (s != NULL)
{
size_t size = strlen (s) + 1;
sdup = malloc (size);
if (sdup != NULL)
{
memcpy (sdup, s, size);
}
}
return sdup;
}