Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using sizeof() on malloc'd memory [duplicate]

Tags:

People also ask

Does sizeof work for malloc?

The malloc line allocates a block of memory of the size specified -- in this case, sizeof(int) bytes (4 bytes). The sizeof command in C returns the size, in bytes, of any type. The code could just as easily have said malloc(4), since sizeof(int) equals 4 bytes on most machines.

How many parameters does malloc have?

The two key dynamic memory functions are malloc() and free(). The malloc() function takes a single parameter, which is the size of the requested memory area in bytes. It returns a pointer to the allocated memory.


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?