Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

c - No out of bounds error

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

#include<stdio.h> 
# define NEWLINE '
'
int main()
{

char c;
char str[6];
int i = 0;
while( ((c = getchar()) != NEWLINE))
{
        str[i] = c;
        ++i;
        printf("%d
", i);
}

return 0;
}

Input is: testtesttest

Output: 1 2 3 4 5 6 7 8 117 118 119 120

My questions are:

  1. Why don't I get an out of bounds (segmentation fault) exception although I clearly exceed the capacity of the array?

  2. Why do the numbers in the output suddenly jump to very big numbers?

I tried this in C++ and got the same behavior. Could anyone please explain what is the reason for this?

question from:https://stackoverflow.com/questions/65929445/unlimited-space-when-array-is-declared-in-heap

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  1. C doesn't check array boundaries. A segmentation fault will only occur if you try to dereference a pointer to memory that your program doesn't have permission to access. Simply going past the end of an array is unlikely to cause that behaviour. Undefined behaviour is just that - undefined. It may appear to work just fine, but you shouldn't be relying on its safety.
  2. Your program causes undefined behaviour by accessing memory past the end of the array. In this case, it looks like one of your str[i] = c writes overwrites the value in i.
  3. C++ has the same rules as C does in this case.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...