No out of bounds error

后端 未结 7 678
既然无缘
既然无缘 2020-11-22 01:01

I have this code in C which takes in bunch of chars

#include 
# define NEWLINE \'\\n\'
int main()
{

char c;
char str[6];
int i =         


        
7条回答
  •  情深已故
    2020-11-22 01:24

    When you access an array index, C and C++ don't do bound checking. Segmentation faults only happen when you try to read or write to a page that was not allocated (or try to do something on a page which isn't permitted, e.g. trying to write to a read-only page), but since pages are usually pretty big (multiples of a few kilobytes; on Mac OS, multiples of 4 KB), it often leaves you with lots of room to overflow.

    If your array is on the stack (like yours), it can be even worse as the stack is usually pretty large (up to several megabytes). This is also the cause of security concerns: writing past the bounds of an array on the stack may overwrite the return address of the function and lead to arbitrary code execution (the famous "buffer overflow" security breaches).

    The values you get when you read are just what happens to exist at this particular place. They are completely undefined.

    If you use C++ (and are lucky enough to work with C++11), the standard defines the std::array type, which is an array that knows its bounds. The at method will throw if you try to read past the end of it.

提交回复
热议问题