C language behaviour

By mistake I wrote the following program and it compiles and runs without any error in gcc compiler.
enter code here

#include<stdio.h>
#include<stdlib.h>
int main()
{
int i,**data;
data=(int **)malloc(sizeof(int)*1000000);
for(i=0;i<1000000;i++)
data*=(int *)malloc(sizeof(int)*1000000);
printf("done

");
return 0;
}

But I don’t understand how is it allocating an array of 1000000*1000000 bytes,almost equivalent to 1TB??

There is a concept called Over-commitment of Memory . Read more about it here, section 9.6

To disable over-commit, you can use (if running on a Linux machine)

echo 2 > /proc/sys/vm/overcommit_memory

malloc() returns NULL when the memory is not available. Your program gets compiled because compiler doesn’t know about it, malloc() kicks in during runtime. You can use valgrind to detect these issues though. In C you can cut your own head off, which is not that easy in other programming languages.

ManPage of malloc() says

By default, Linux follows an optimistic memory allocation strategy. This means that when malloc() returns non-NULL there is no guarantee that the memory really is available.

Malloc returns a pointer to a block of memory only if it is possible to allocate memory otherwise it returns NULL. Hence in this case you get NULL once the heap memory is full. changed your code to the following(run on ideone) :

#include<stdio.h>
int main()   {
int i,*data;
data=(int *)malloc(sizeof(int)*1000000);
for(i=0;i<1000000;i++)
{
data*=(int *)malloc(sizeof(int)*1000000);
if(data*==NULL)
{	
  printf("Memory full at %d

",i);
break;
}
}
printf("Done
");

return 0;

 }

I got the output as :

Memory full at 140
Done

As you can see malloc only allocates memory on the first 140 occasions and returns NULL thereafter.

3 Likes