1

I was asked this question in a interview, what is the minimum size malloc can allocate and what is the max size a malloc can allocate.

I answered min size if 1 byte, and when I told that he replied assuming that is correct now tell me what is the max size memory chunk can malloc allocate( when you try doing malloc it fails sometime), think you have 4GB of RAM with you write me a code to find the size of heap segment for your simple program you write or write me a code to find the size of stack segment.

Can any one help me in this solution.

Is the minimum size it can allocate is 1 byte? I answered thinking char requires the least memory.

Maroun
  • 94,125
  • 30
  • 188
  • 241
Manu
  • 5,534
  • 6
  • 32
  • 42
  • Some implementations of `malloc()` may even successfully allocate `0` bytes. So I'd sure go for `1` byte is always possible. – alk Sep 01 '13 at 12:51
  • 1
    Does this help:- http://stackoverflow.com/questions/6389120/malloc-memory-allocation-scheme-in-c ??? – Rahul Tripathi Sep 01 '13 at 12:51
  • what code have you got so far? you could start with malloc(1) and increase the number until malloc fails. should be close to the ram amount that your machine has. – jev Sep 01 '13 at 13:02
  • Another question on how to determine stack's size: http://stackoverflow.com/q/389219/694576 – alk Sep 01 '13 at 13:04

2 Answers2

0

Yes, the minimum size malloc(size_t) is guaranteed to be able to allocate it (size_t) 1.

It is up to the implementation whether requesting 0 bytes would return NULL or not.

C standard (WG14/N1256) 7.20.3:

If the size of the space requested is zero, the behavior is implementationdefined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object

alk
  • 69,737
  • 10
  • 105
  • 255
0

The minimum size malloc can really allocate is 1 byte. According to the C standard (7.22.3), "If the size of the space requested is zero, the behavior is implementation-defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object."

On the other hand, malloc almost definitely will allocate more bytes than 1, even if you call it with size 1. It needs extra bytes for storing additional information, e.g. the size of the allocated memory chunk, which will be needed for deallocation. Furthermore, there are memory alignment issues.

If you were asked to write a program to compute the maximum size malloc can allocate on a given machine of 4GB memory and at a given time, I think you were expected to write a program that used binary search to find the exact maximum. Of course, the answer of the program could be different each time you called it. The same could be done using a stack-allocated variable-sized array, to compute the maximum allowed size for your stack.

nickie
  • 5,608
  • 2
  • 23
  • 37