Possible Duplicate:
newbie questions about malloc and sizeof
I am trying to read strings into a program. When I noticed that the strings were sometimes being corrupted, I tried the following code:
void *mallocated = malloc(100);
printf("sizeof(mallocated) = %d\n", sizeof(mallocated));
According to my program, the size of mallocated was 8, even though I allocated 100 bytes for it. Because of this, whenever I try to store a string longer than 8 bytes, everything after the 8th byte will sometimes disappear. Why is this happening, and how can I prevent it?
Because the size of the “string” pointer is 8 bytes. Here are some examples of using
sizeof()with their appropriate “size”. The termsize_of()is sometimes deceiving for people not used to using it. In your case, the size of the pointer is 8 bytes.. below is a representation on a typical 32-bit system.Source
You are leaving out how you are determining your string is disappearing (char array). It is probably being passed to a function, which you need to pass the explicit length as a variable or track it somewhere. Using
sizeof()won’t tell you this.See my previous question about this and you’ll see even my lack of initial understanding.