-2
#include<stdio.h>
#include<stdlib.h>
int main()
{
    int *a[10];
    a[2] = (int*)malloc(sizeof(int));
    a[2][3]=4;
    printf("%d", a[2][3]);
    return 0;

}

I have given only the memory equivalent of a single int to the pointer variable. How is that I am able to access an element at index 3 for that pointer of a single int?

goelakash
  • 2,502
  • 4
  • 40
  • 56
  • 1
    [Please don't cast the return value of `malloc()` in C](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – unwind Feb 05 '16 at 10:23
  • 1
    Use a memory debugger to catch such issues, such as BoundsChecker or Valgrind. – jxh Feb 05 '16 at 10:24
  • I am not trying to be a klutz here. I just saw this C code, and didn't know if array bounds checking was even optional for languages, as I was naturally expecting an error. – goelakash Feb 05 '16 at 10:38
  • @goelakash Everything is optional for languages, basically. :) It's up to the language designers and implementors to shape the semantics of the language (within the bounds of what the computer can do, of course). – unwind Feb 05 '16 at 10:40
  • Accessing unallocated memory is a subtle because it will end up in **undefined** behavior. Your program can: 1. **Crash Immediately** (*in case you request memory that does not belong to your process*) 2. **Temporarily works** 3. **Works perfectly for the next 100 years.** The final behavior depends on many factors, such as the **combination of compilers/hardware/system**. You example is very simple and works because you are accessing few bytes out of bounds and this is very likely to be a portion of memory that is reserved (but not allocated) to your process – Davide Spataro Feb 05 '16 at 10:41

3 Answers3

1

You can try but the behaviour of your program will be undefined.

C does not perform that kind of checking at runtime.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

That's because nothing is preventing you accessing arrays out of bound and this invokes undefined behavior. Any expected or unexpected behavior of program can be seen.

haccks
  • 104,019
  • 25
  • 176
  • 264
1

You're accessing some randomly set RAM element. This is a common C programming mistake and is one of the reason for many security flaws.

The Heartbleed bug would be a nice example, where people were able to read a good portion of the server RAM, by accessing elements outside of the array structure.

CodeMonkey
  • 4,067
  • 1
  • 31
  • 43