Accessing out-of-bounds elements of dynamically allocated arrays / w/o SegFault

前端 未结 4 2073
粉色の甜心
粉色の甜心 2021-01-24 18:48

I\'m developing a program in C that uses an array of linked lists (a primitive hash table) as a data type to represent certain date information. The array has twelve elements c

4条回答
  •  醉酒成梦
    2021-01-24 19:35

    In C, accessing an array outside its bounds is undefined behavior.

    That means that anything can happen, including the program behaving as you might expect it to.

    The C language doesn't require bounds checking on array accesses, and most C compilers don't implement it.

    For example, suppose you declare:

    int before;
    int array[10];
    int after;
    

    The order in which these are stored in memory is undefined, but suppose they're stored contiguously in the order they're declared. If you attempt to access array[-1], you might access before instead. If you attempt to access array[10], you might access after instead.

    The burden is on the programmer to avoid accessing arrays outside their bounds. Or there might not be anything allocated before and/or after your array.

    An analogy: "The sign says I'm only allowed to cross the street when the light is green. I crossed on red, and nothing happened. Why didn't a car hit me?" (There are languages that go out of their way to make the car hit you. C isn't one of them.)

提交回复
热议问题