You are not logged in. Please login at www.codechef.com to post your questions!

×

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[i]=(int *)malloc(sizeof(int)*1000000);
printf("done\n");
return 0;
}

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

asked 28 Jan '14, 18:24

amit09's gravatar image

3★amit09
31235
accept rate: 0%

edited 28 Jan '14, 18:28

kcahdog's gravatar image

3★kcahdog
10.0k2854129


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[i]=(int *)malloc(sizeof(int)*1000000);
if(data[i]==NULL)
{   
  printf("Memory full at %d\n",i);
break;
}
}
printf("Done\n");

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.

link

answered 28 Jan '14, 19:02

kcahdog's gravatar image

3★kcahdog
10.0k2854129
accept rate: 14%

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.
link

answered 28 Jan '14, 18:46

bugkiller's gravatar image

3★bugkiller
8.7k194898
accept rate: 9%

edited 28 Jan '14, 20:33

toggle preview
Preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported
  • mathemetical formulas in Latex between $ symbol

Question tags:

×1,490
×107
×26

question asked: 28 Jan '14, 18:24

question was seen: 1,095 times

last updated: 28 Jan '14, 20:33