0

I am having a odd issue running scientific linux in VirtualBox when compiling this:

#include <stdlib.h>
#include <stdio.h>

int main(void) {
    int *arr;
    arr = malloc(sizeof(int)*3);
    arr[6]=5;
    printf("%d", arr[6]);

    return 0;
}

my expectation is that I should get garbage when printing out this arr[6] because I have not allocated enough memory for that space.

However, I will compile it with gcc

gcc main.c -o MainTest

then it will output

5

I may be a bit confused but shouldn't the number be some random number

cat
  • 91
  • 10
  • 6
    Accessing outside of allocated array bounds is undefined behavior, you should not have any expectations as to the results. – Shafik Yaghmour Aug 30 '13 at 11:56
  • 3
    `...shouldn't the number be some crazy garbage number.` You want to say, it should not be this type of UB, it should be a different type of UB. :-) – 0xF1 Aug 30 '13 at 12:00
  • @nishant Ha! I understand you are making a reference towards my nomenclature (or lack thereof) however, I do not understand what "UB" is? – cat Aug 30 '13 at 12:07
  • @cat `UB` = [Undefined Behavior](https://en.wikipedia.org/wiki/Undefined_behavior). – Shafik Yaghmour Aug 30 '13 at 12:10
  • Is `5` not random enough for you? [Would 4 work better?](http://xkcd.com/221/) – abelenky Aug 30 '13 at 13:02

2 Answers2

1

I may be a bit confused but shouldn't the number be some crazy garbage number.

Why? You wrote 5 there. Of course, you wrote into "out of bounds" space, which is an issue. How an implementation should deal with that is not specified by the C standard, which is the point of undefined behavior, but if it just plain does it, what will (generally) happen is either you are still within the process's address space, or else the OS will hand you a segmentation fault (aka. memory access violation) at runtime. Note that this is not determinable at compile time and may vary from run to run and system to system (more points about undefined behavior).

If you are still within the process address space, you still have a significant problem, because you may have overwritten something that was allocated for some other purpose; C will not protect you from that and this can produce very nasty hard to solve bugs.

CodeClown42
  • 11,194
  • 1
  • 32
  • 67
0

Have a look at this link : Sample Code

What i have observed is *arr is storing the starting address of the array and as you are initializing a[6]=5 whats happening is arr+6 the sixth location in the memory from starting is getting filled up with the value you have put and at the time of printing as it is a valid address its printing the value in the address

Update 1:
As long as the value is not modified by other process it outputs the value in that address space.

VJ Sai
  • 175
  • 1
  • 2
  • 10