malloc ( )

Axel Freyn
Wed Aug 31 13:29:00 GMT 2011

Hi Avinash,
On Wed, Aug 31, 2011 at 06:12:41PM +0530, 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.
GCC is right whatever happens, your code is illegal C (so you get
"undefined behaviour" :-)).
> 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) ?
> Please guide me.
You are misunderstanding C. For general C-questions there are more
adequate mailing lists.
According to the C language, "256" is understood as an integer number of
type "int" with the value 256. The memory size (=number of bits needed &
used) for an "int" is ABSOLUTELY INDEPENDENT of its value -- "1" needs
as many bits as "256" (simply starting with some "0"-bits). The precise
size of an "int" depends on your hardware, the only limitation is that
it has to have at least 2 bytes (maybe that limit got increased with
newer C-standards?).
So: 256 needs 16 bits or more.

When you call now "malloc(1)", this library function returns you a
memory address at which you have at least 1 byte "free" which is
reserverd for you and won't be used by anybody else (if all code is
written correctly). You write now 2 or more bytes at this address. This
 - the first byte is fine.
 - the second and all following bytes are written in a memory range,
   which MIGHT BE used for something else.
So many different things can happen:
 - nobody uses this region. Then the code runs fine (but nobody
   guarantees it will run correctly when you restart it).
 - the implementation of malloc on your machine always reserves MORE
   memory (e.g. 4 bytes) -- then your code works always ON YOUR MACHINE,
   you don't know what will happen on other machines
 - another variable of your program is stored there: then that variable
   is overwritten / might overwrite p
 - your operating system does not allow your program to access this
   memory address (e.g. because it was distributed to another user).
   Then your code get's killed by the operating system
 - ......


More information about the Gcc-help mailing list