-1

I was trying to access a variable through array which is out of bound index like this

#include <stdio.h>
int main(void){

    int x = 8;
    int arr[10];
    int *ptr = &x;

    printf("the address of x is : %d\n" ,ptr);
    printf("the address of arr[10] is :   %d\n", &arr[10]);
 
    printf("arr[10] = %d\n",arr[10]);
    printf("x = %d\n",x);

    return 0;
  }

The output is

    the address of x is : 6422296
    the address of arr[10] is :6422296
    arr[10] = 8
    x = 8

Can I use this technique to access any useful data or any application for this? Or is it just a useless code that spits out garbage values?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 4
    It's [undefined behavior](https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior). It happens that on your current system, with your compiler, with that version, it *happened* to be the case that `x` was just after `arr` in memory. – nanofarad Aug 10 '23 at 15:08
  • 6
    Basically _"it just a useless code that spits out garbage values"_ is a very true statement. – Jabberwocky Aug 10 '23 at 15:18
  • The compiler may arrange them in any order it likes. In some cases they may be optimised so that they are not in memory at all. – Weather Vane Aug 10 '23 at 15:46
  • Note what it says in [Correct format specifier to print pointer or address?](https://stackoverflow.com/q/9053658/15168) – Jonathan Leffler Aug 10 '23 at 16:21
  • Make sure that you copy and paste your working code into your question. The code you had could not compile because it had `printf(10"…", …);`, and even with that fixed, could not produce your claimed output because it used `/n` instead of `\n` in the print formats. Details like this matter. I fixed the egregious typos because they were not really germane to your question, but often, such issues would mean the question has to be closed until you fix it. – Jonathan Leffler Aug 10 '23 at 16:25

0 Answers0