C Programming - Memory Allocation - Discussion

7. 

How many bytes of memory will the following code reserve?

#include<stdio.h>
#include<stdlib.h>

int main()
{
    int *p;
    p = (int *)malloc(256 * 256);
    if(p == NULL)
        printf("Allocation failed");
    return 0;
}

[A]. 65536
[B]. Allocation failed
[C]. Error
[D]. No output

Answer: Option B

Explanation:

Hence 256*256 = 65536 is passed to malloc() function which can allocate upto 65535. So the memory allocation will be failed in 16 bit platform (Turbo C in DOS).

If you compile the same program in 32 bit platform like Linux (GCC Compiler) it may allocate the required memory.


Ravi said: (Aug 16, 2011)  
Why this is not producing anything in gcc compiler also ?

#include<stdio.h>
#include<stdlib.h>

int main()
{
int *p;
p = (int *)malloc(256 * 250);
if(p == NULL)
printf("Allocation failed");
return 0;
}

Even output screen vanishes ?

Cherry said: (Jun 30, 2012)  
In 16-bit platform the range is 0 to 65535 but here p gives 65536. So that p=NULL. Then it prints if statement.

I hope you understand.

Lav said: (Dec 16, 2012)  
@Cherry, // TurboC++(16-bit).

But for p=(int *)malloc(65534); also o/p: Allocation failed.

Sudheer said: (Aug 16, 2013)  
So the options should be like compiler dependent or system dependent ?

Otherwise it will allocate the memory (if system is 32 bit or higher) , so it should be A and not B as it is NOT true for all cases.

Kalle said: (Oct 1, 2013)  
Please remove this absurd question! (Or tell us you mean a 16 bit platform).

We already had to assume the memory was available.

Sandi said: (Jun 20, 2014)  
Please mention it is 16 bit platform, otherwise 4th option can be correct.

Jennt said: (Apr 13, 2015)  
Yes, with 32 bit memory addresses both [A] and [D] options can be correct, if you're considering machine/platform dependent constraints give us a little context.

V1Ron said: (Sep 27, 2015)  
Incorrect question. No one uses DOS nowadays. There may be a bunch of platforms with individual limits.

Aadesh said: (Mar 8, 2016)  
16 bit is a compiler not memory which basically related to processor that upto which byte the processor can access the memory. Therefore the memory must get allocated.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.