Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

malloc(sizeof(s)) allocates less memory than expected?

Tags:

c

malloc

hey i am having problems using the sizeof operator in malloc. For example see the foll. code-

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char * copy(char *s)
{
    char *t=malloc(sizeof(s));
    char *ptr=s;
    int i=0;
    do
    {
        t[i++]=*ptr++;
    }
    while(*ptr!='\0');
    return t;
}
int main()
{
    char *s="hello adsjahsjkdhjkashdkjaskdasldjlasjdlajsdlkjaslkdjalsjdlasjdljasdljasdkljklsdjlasdsadasdasd";
    char *b=copy(s);
    printf("%s\n",b);
    free(b);
    return 0;
}

on ideone, it gives the error:- * glibc detected ./prog: free(): invalid next size (fast): 0x09bcf008 **

But when i replace malloc(sizeof(s)) with malloc(strlen(s)+1) , the program works perfectly. So whats the problem? NOTE:this is just a small prog i created to demonstrate the problem i was having in another code.

like image 937
ksb Avatar asked May 26 '26 14:05

ksb


1 Answers

The operator sizeof doesn't do what you want on pointers. It yields the size of the pointer on your machine (which will be something like 4 or 8).

You can think of it this way: the array decays to a pointer when passed to a function and the information regarding its size is "lost".


Also note your loop doesn't fill in the 0 terminator.

like image 146
cnicutar Avatar answered May 30 '26 03:05

cnicutar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!