newbie questions about malloc and sizeof

sizeof(str) returns the size of a pointer of type char*. What you should do is to malloc the size of the string it self:

char * copy = malloc(strlen(str) + 1);

Also, these lines:

while(*str != '\0'){
        *copy = *str;
        str++;
        copy++;
}
copy = '\0';

Can be rewritten easily in C like this:

while(*copy++ = *str++);

Leave a Comment