Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

newbie questions about malloc and sizeof

Tags:

c

malloc

sizeof

Can someone explain to me why my call to malloc with a string size of 6 returns a sizeof of 4 bytes? In fact, any integer argument I give malloc I get a sizeof of 4. Next, I am trying to copy two strings. Why is my ouput of the copied string (NULL)? Following is my code:

int main()
{
    char * str = "string";
    char * copy = malloc(sizeof(str) + 1);
    printf("bytes allocated for copy: %d\n", sizeof(copy));
    while(*str != '\0'){
        *copy = *str;
        str++;
        copy++;
    }
    copy = '\0';
    printf("%s\n", copy);
}
like image 859
John Avatar asked Oct 07 '09 19:10

John


1 Answers

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++);
like image 86
Khaled Alshaya Avatar answered Sep 20 '22 02:09

Khaled Alshaya