Reputation: 127
I am reading the book "Expert C Programming", but here is the code that really confused me. I can't understand the use of the function malloc and the value it returns here, and why running this will return the memory allocated in the process? Thanks in advance.
#include<stdio.h>
#include<stdlib.h>
main()
{
int MB = 0;
while(malloc(1<<20)) ++MB;
printf("Allocated %d MB total\n",MB);
}
Upvotes: 2
Views: 115
Reputation: 343
unsigned int
A = 1 << 0, //1 byte 2^0 0x00000001 0b00000000000000000000000000000001
B = 1 << 8, //256 byte 2^8 0x00000100 0b00000000000000000000000100000000
C = 1 << 10,//1024 byte 1KB 2^10 0x00000400 0b00000000000000000000010000000000
D = 1 << 20,//1048576 byte 1MB 2^20 0x00100000 0b00000000000100000000000000000000
E = 1 << 28;//256 e6 byte 1GB/4 2^28 0x10000000 0b00010000000000000000000000000000
const int TOP = 100;//25GB max
void* p[TOP] = {};
for (int i = 0; i < TOP; i++) //32 bit system max 2Gb
{
p[i] = malloc(0x10000000); //1GB/4 or 256Mb
//p[i] = malloc(1<<28);
//p[i] = malloc(E);
printf("%4d 0x%08x\n", i, p[i]); //32 bit system
//printf("%4d 0x%016llx\n", i, p[i]); //64 bit system
}
for (int i = 0; i < TOP; i++)
free(p[i]);
Upvotes: 1
Reputation: 56
The <<
operator does a bit-wise left shift. So this shifts binary 1 left by 20 positions.
i.e. 0000 0000 0000 0000 0001 becomes 1000 0000 0000 0000 0000.
This is equivalent to 1 MB since a MB is defined as 2^20.
Therefore each malloc()
call tries to allocate 1 MB. malloc()
will return NULL if it cannot allocate this much space. In C, NULL will evaluate to False.
Therefore, in each iteration of the loop, the program will allocate 1 MB. If it's successful, it increases the MB counter. If malloc()
runs out of space, it will return NULL and end the loop. The printf
statement will then print the amount of memory that was allocated.
Upvotes: 3