Yahoo Interview Question
Software Engineer / Developerswhen we call malloc it returns a pointer to the heap, it returns memory in multiple of blocks, each block size depends on implementation of malloc, malloc is going to round of to next integer multiple of block. so its going to return atleast one block. so thats why there won't be problem even if we try to assign value to memory.
Yes, it's implementation dependent. Thanks mondac!!
I got 2 different results for 2 different compilers when i say
printf("%p, %d",p,*p);
GCC: 0x804a008 , 0
MS VC++: 00030850, -33686019
TC : 00000 , 0
GCC
>
>> I really hate it when people ask such questions, I am wondering,
>> they just want to pull of peoples tolerance levels towards such
>> questions, Instead they could beat him with a stick and watch if
>> get angry:)
>
No, this isn't about measuring someone's tolerance level, it's about measuring an individual's understanding of the C language. Few, if any, programmers, would knowingly use malloc() to allocate 0 bytes of memory. However, it would be very easy to pass an argument to malloc() that somehow got incorrectly set to zero. The interviewer wants to know if you understand what will happen if such a situation occurs. This is going to be important when you attempt to find the bug that has set the variable in question to a value of zero.
The correct answer to this question is that the result is compiler dependent. However, the most likely behavior is that a non-zero length memory segment will be returned by malloc(). Malloc is guaranteed to return *at least* the number of bytes you request, but may return a contiguous memory segment larger than the requested size if it wishes. Since some malloc() implementations maintain "bins" of preallocated memory it's possible that the size of the memory segment returned will be small, but not zero. Perhaps 8, 16, or 32 bytes in length.
void * Myalloc ( int size )
{
// lets assume we get the address of the available memory in a;
// n be the available size
void *f =a // now f is the void pointer which points to the available memory )
if( size > N )
printf(" in sufficient memory ");
else
n=n+size ;// size is reduced from availabe n
return f;
}
so it will always give a valid address
Correct me if i am wrong
It is not true that malloc will always return at least 1 byte.
int * p= NULL;
p = (int*) malloc(0);
what will be the value of p?
The value of is implementation dependent.
7.20.3 (n869):
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.
I think it is implementation-dependent.
- hunt September 23, 2009