0

Let's assume I want to build myself a c like "string". Why does this code not throw an error when I assign array[6]? Does char array[6] not give me index 0-5? Has this something to do with stack vs heap?

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

int main()
{
    char array[6];
    array[6]='\0';

    if (array[6]=='\0'){
        printf("yes");
    }
    else printf("no");

    return 0;
}
FoggyDay
  • 11,962
  • 4
  • 34
  • 48
Nivatius
  • 260
  • 1
  • 13
  • 1
    It's called [undefined behavior](https://en.wikipedia.org/wiki/Undefined_behavior) – FoggyDay Feb 27 '20 at 20:24
  • so the answer is: because the makers of my compiler tried to be nice and it does something that is not defined in the standard? – Nivatius Feb 27 '20 at 20:31
  • 1
    No, it's because nothing in the standard says the compiler *must* crash if you access an element that's out of bounds. See this thread: https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior or this article: http://theunixshell.blogspot.com/2013/07/what-is-undefined-behavior.html – FoggyDay Feb 27 '20 at 20:33
  • okay, it's just something I've come to expect from python. (which throws an out of bounds error)- that's one of those sharp edges of c/c++. Quote from the linked answer: " Undefined behavior is one of those aspects of the C and C++ language that can be surprising to programmers coming from other languages (other languages try to hide it better). Basically, it is possible to write C++ programs that do not behave in a predictable way, even though many C++ compilers will not report any errors in the program!" this must be a common question so thank you for taking the time again. – Nivatius Feb 27 '20 at 20:41

1 Answers1

-1

Let's first look at array[0] which is just a pointer to the first character. By giving the array notation with a char type you have said that array[1] should offset the pointer by 1 byte(size of a char). So when you say array[6] you are moving the pointer outside of the allocated memory block which will cause undefined behaivour.

Jonathan L
  • 34
  • 4
  • I know it's wrong, but why does it even let me assign outside of allocated memory? – Nivatius Feb 27 '20 at 20:32
  • 1
    That is because the array is just syntactic sugar for pointer arithmetic. It's just moving the pointer around which is perfectly valid. – Jonathan L Feb 27 '20 at 20:33
  • To clarify your pointer will still be pointing on a valid memory location so it is fine for you to retrieve or store value on those locations. – Jonathan L Feb 27 '20 at 20:36