1
#include <stdlib.h>
#include <stdio.h>
#include <ctime>      // For time functions
#include <math.h>     // For pow()
#include <iostream>
using namespace std;

int main()
{

      int jiff=50;
      int sizes[jiff]; //array of size jiff

    sizes[49]=50;  //existing, should be last position
    sizes[55]=4;    //should not exist

    printf("it is %d\n", sizes[49]);
    printf("it is %d",sizes[55]);
}

output:

it is 50
it is 4

Why doesn't my code crash? sizes[55] should be out of bounds and should crash at run-time. What gives?

EDIT: Nevermind, it crashes sometimes now, or it prints out obscurely large numbers. My new question: Why was it not misbehaving earlier? My first 5 runs were flawless for any array position up till 60

user3507072
  • 287
  • 1
  • 4
  • 13
  • If you're programming in C, memory management should be made on your own. Like in your code sizes[55] = 4; is indeed *(sizes + sizeof(int) * 55) = 4; which dereferencing a pointer address and assign the value to it. If that address is valid, the CPU will let it go and overwrite a memory area that you have NOT allocated. – Ken Cheung Oct 14 '14 at 03:30

2 Answers2

1

Accessing memory that was not allocated to you causes undefined behavior. Sometimes, it might print whatever happens to be sitting at that memory address and sometimes it might give you a segmentation fault. See this question for a list of common undefined behaviors

Community
  • 1
  • 1
dramzy
  • 1,379
  • 1
  • 11
  • 25
  • I agree. As of now, my output should be whatever happens to be at that memory address. But believe me when I say that the first 5 runs produced 0 errors, and the number 4 DID print out at array position 55. I'm just curious why it didn't misbehave to begin with. – user3507072 Oct 14 '14 at 03:26
  • This whole situation seems trivial and non-important, but are there cases where things that should error out dont? And if so, how? – user3507072 Oct 14 '14 at 03:27
  • Yeah, it let you assign a 4 to that chunk of memory, but the other times you tried, it didn't. That's why it is undefined. – dramzy Oct 14 '14 at 03:28
  • I guess my understanding of undefined wasn't well defined :) Thanks – user3507072 Oct 14 '14 at 03:29
1

You're correct that it's out of bounds, but it will not necessarily crash (although it's a distinct possibility).
When you do sizes[55]=4; it will happily write 4 into the memory location 5 ints past the end of your array.
But who's memory is that? It could be another part of your code, it code be another app's code. If it's another app's code it'll probably crash right away. If it's your own code, it could cause your code to crash in bizarre and hard to debug ways that don't seem related to this piece of code. Rest assured that even though it doesn't seem to cause a problem, it will come back to haunt you later.

JBY
  • 238
  • 2
  • 10