C-malloc and array confusion

I tried to understand 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 that meant that only 5 elements could be added to the array. To check if this is 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, this code compiled and works just fine. How is this possible?

+7
source share
4 answers

C does not apply array bounds checking, so if you requested a space for 5 integers, you used more.

In fact, you overwrote 4 memory cells that really were not reserved for your specific purpose. Your program walked past the memory area that was allocated for your array, and began to store values ​​in memory outside the allocated area.

The fact that this "worked" is just luck, and not what it depends on. It may work the next 100 times, or it may not work the next time it is tried, with the likely message "segmentation error."

Defensive programming, as you did, intelligently checking the return value of malloc, remembering that you are responsible for checking boundaries, compiling code with higher levels of warnings, etc. - here are some of your best defenses against such errors. Other tools like valgrind can also help check font types, but in the end it is up to you.

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

+9
source

C does not perform bounds checking.

0
source

How is this possible?

You write the end of the array. This does not cause the program to crash (right away), since the C test is not performed, however, if you write far enough, it will ultimately cause an error. From time to time, you can write hundreds of int values, and in other cases, you will not be able to write extra ones.

0
source

The memory on your computer is basically laid out sequentially. You asked malloc to give you a small portion of this memory - enough for 5 ints. There is definitely more memory on your computer than it takes to allocate an array of length 5. Therefore, if you write or read from arr[8] , you write somewhere else in memory.

Usually modern computers have so much memory that you probably write somewhere that is not used. But sometimes you accidentally overwrite some other malloc 'd data.

Please note that sometimes your program crashes (as expected). This is because you can try to write so far outside the allocated memory that the address is no longer valid. Your OS usually catches this and gives you your program.

0
source

All Articles