malloc ( )

John Fine johnsfine@verizon.net
Thu Sep 1 00:14:00 GMT 2011



Avinash Sonawane wrote:
> How malloc can store it at 'p'
> since I have allocate only 1 byte of memory 
>   
...
>   p=(int *) malloc(1);
>
>   *p=256;
>
>   
Bugs in your program don't always have symptoms.  The lack of a symptom 
never proves the lack of a bug.

When you ask for just 1 byte of memory, a typical version of malloc will 
allocate at least enough to store an int.  It gives you the address of 
the first byte of that and it leaves the rest unused.  So your bug has 
no symptom.

The reason malloc allocates enough for at least an int and leaves the 
rest unused, is NOT to avoid problems when malloc is misused as you 
did.  It is because it happens to be very inconvenient to manage really 
tiny allocations.

Nothing in the C standard implies malloc will leave enough room to cover 
up your bug.  Most versions of malloc will.  Some won't.



More information about the Gcc-help mailing list