Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Malloc and array index confusion in C

Tags:

arrays

c

malloc

I was trying to grasp the malloc function in C, and I wrote the following code:

int i;

int *arr = (int*)malloc(5*sizeof(int)); 

if(arr==NULL){

  printf("Failed to allocate memory for arr...\n");
  exit(1);

}

I thought this meant that only 5 elements could be added to the array. To test out if that was true, I added the following code:

arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;
arr[5] = 6;
arr[6] = 7;
arr[7] = 8;
arr[8] = 9;

for(i=0;i<9;i++){

    printf("%d\n",arr[i]);

}

Surprisingly, that code compiled and ran perfectly. How was that possible?

like image 932
niravb Avatar asked Jul 18 '12 22:07

niravb


1 Answers

C doesn't enforce any array bounds checking, so while you requested space for 5 integers, you used more.

In fact you overwrote 4 memory locations that really weren't set aside for your specific purpose. Your program went past the area in memory that was set aside for your array, and started to store values in memory outside the allocated region.

The fact that this "worked" is just pure luck and not something to be dependent on. It may work the next 100 times, or it may fail the next time you try it, with most likely a "segmentation fault" message.

Defensive programming, like you did by sensibly checking the return value of malloc, being mindful that you are responsible for bounds checking, compiling code with high warning levels enabled, etc are some of your best defenses to guard against these sort of errors. Other tools, such as valgrind, lint type checkers can also help, but at the end it's up to you.

One of C's greatest strengths, its freedom to do all sorts of things, low and high-level, is also one of its greatest weaknesses IMO. If Java is a Volvo, C is perhaps more like a Ferrari with spotty breaks at times :)

like image 129
Levon Avatar answered Oct 22 '22 09:10

Levon