Security Basics mailing list archives

Re: question about malloc()


From: Chris Umphress <umphress () gmail com>
Date: Wed, 14 Sep 2005 14:26:49 -0700

I am studying on exploitation.
But my knowldge of c programming is very limited.
I studied c language 10 yrs ago and never used it.
Now i am having some problems.

I have a question about exploit example of my book.

----------------------------------
...
char *buf;
buf = malloc(1<<30);
fgets(buf, 1024, stdin);
printf("%s\n", buf);
...
----------------------------------

Can anyone explain this? This should be very simple...
when I put buf = malloc(1<<29), it is working...

malloc() allocates memory. The example you have is manipulating bits
to define how large the buffer it creates should be. It is putting a
one at the 31st bit position (shifting the 1 over thirty bits), which
becomes the decimal number 1073741824. This is how many bytes it is
allocatiing. Divide it by 1024 three times, and you'll realize that it
is trying to allocate a gigabyte of memory. Shifting the one bit over
29 spaces translates into "only" 512MB of memory.

The point of the exercise is to show you what will happen if malloc
fails to allocate the memory as you expected it to. There is
absolutely no testing to make sure that the program is writing data to
an area of memory that it has control over.

-- 
Chris Umphress <http://daga.dyndns.org/>


Current thread: