malloc ( )

Jonathan Wakely
Wed Aug 31 12:57:00 GMT 2011

On 31 August 2011 13:42, Avinash Sonawane wrote:
> Respected Sir,
> I am using gcc version 4.5.2 (Ubuntu/Linaro 4.5.2-8ubuntu4)
> I have one doubt regarding malloc () in gcc.

That's not a doubt, it's a question, and it's not a question about gcc
so is not really appropriate on this mailing list.

> When I tried to execute the program given below, it got executed.
> But since 256 = 1 0000 0000 (9 bits) , How malloc can store it at 'p'
> since I have allocate only 1 byte of memory (8 bits of memory) ?

The program is invalid, it is your responsibility to use malloc
correctly to avoid errors like this.

When you call malloc(1) it doesn't create a new piece of memory of 1
byte, isolated from the rest of your computer's memory. It simply
returns you a memory address, which points to a block of at least 1
byte.  When you write 4 bytes to that address you are overwriting 3
by7tes which you did not get from malloc. That could corrupt your heap
memory, or have other nasty effects, possibly eventually causing your
program to crash, or worse.

More information about the Gcc-help mailing list