Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C array setting of array element value beyond size of array

Tags:

arrays

c

I Have this C code snippet

int numbers[4]={1};

numbers[0]=1; numbers[1]=2; numbers[3]=3; numbers[10]=4;
printf("numbers: %d %d %d %d %d %d\n",numbers[0],numbers[1],numbers[3],numbers[6],numbers[10],  numbers[5]) ;

The Output for this snippet produces :

    numbers: 1 2 3 963180397 4 0

Well I have couple of questions

  1. wont setting numbers[10] give an error as array is just of size 4 if not then why ( as it didn't give any error )

  2. why printing numbers[6] gives garbage value whereas numbers[5] gives value of 0 ? shouldn't it also be a garbage value.

  3. what effect does setting numbers[10] has i know it does not increases size of array but what does it do then?

Thanks in advance . PS i used GCC to compile the code!!

like image 403
pyth Avatar asked Dec 29 '25 17:12

pyth


1 Answers

  1. This won't give an error, your array is declared on the stack so what number[10] does is write at the adress number + (10*sizeof int) and overwrites anything that would be there.
  2. As Xymostech said 0 can be as much garbage as 963180397. Printing numbers[6] will print what is stored at the address numbers + (6*sizeof int) so it depends on how your program is compiled, if you have declared local variables before of after numbers, etc.
  3. See answer 1.

What you can do is this :

int empty[100];
int numbers[4]={1};
int empty2[100];

memset(empty, 0xCC, sizeof empty);
memset(empty2, 0xDD, sizeof empty2);

numbers[0]=1;numbers[1]=2;numbers[3]=3;numbers[10]=4;
printf("numbers: %d %d %d %d %d %d\n",numbers[0],numbers[1],numbers[3],numbers[6],numbers[10],  numbers[5]) ;

Now you can understand what you are overwriting when accessing out of your numbers array

like image 155
koopajah Avatar answered Jan 01 '26 09:01

koopajah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!