1

Java / C++ developer here. Trying to learn C but I am confused with memory allocation for arrays.

What is happening here?

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

int main()
{
    int az[3];
    az[2] = 66;
    az[8] = 5214;

    printf("%d\n", az[8]);

    system("pause");
    return 0;
}

Output

5214

How can that be ? Why do I not get Out of Bounds exception or a program crash? I can I do this infinitely? What is my array's length in this case? What's the point of allocating memory via malloc if my arrays allow me to already put values out of bounds? This makes zero sense to me.

enter image description here

jww
  • 97,681
  • 90
  • 411
  • 885
Hatefiend
  • 3,416
  • 6
  • 33
  • 74
  • C does not complain about out of bounds. Simple as that. – icbytes Jul 17 '16 at 00:19
  • 1
    Behavior is 'undefined', which means exactly that. Could crash. Could print garbage. Could sigsegv. Could start up a copy of minecraft. C/C++ doesn't have guardrails. – evaitl Jul 17 '16 at 00:22
  • 1
    FYI you can do the same thing in C++; it is not unique to C or malloc. – Nicholas Smith Jul 17 '16 at 00:28
  • Note that accessing out of bounds usually only crashes if beyond that bound lies memory that does not belong to your process. But in this case, you just access the local frame (usually the stack) and accessing that does not necessarily cause an immediate crash. – Rudy Velthuis Jul 17 '16 at 01:42
  • Please use search before asking questions. – 2501 Jul 17 '16 at 08:03

1 Answers1

6

C does not perform any bounds checking. Indexing an array of length 3 with index 8 may (appear to) work just fine, may subtly corrupt other memory used by your program, or may cause an immediate segmentation fault depending on how that particular array is laid out in memory.

This type of error could be called a "buffer overflow" and is a common cause of security vulnerabilities, as not checking the bounds of an array before indexing it can result in malicious modifications to your program at runtime.

Welcome to the crazy and exciting world of C coding!

thewmo
  • 755
  • 5
  • 7