Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c++ Segmentation fault when trying to reverse print an array

I have a array consisting of chars like [1,2,3,4,5,.,..] and I have a loop that looks like

  for (size_t i = 0; i < size; ++i)
    os << data[i]; // os is std::ostream&

This loop prints the array in the correct order without any errors. But when I use this loop to print it backwards

  for (size_t i = (size - 1); i >= 0; --i)
    os << data[i];

I get a segmentation fault error. Any reason why this can happen?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The condition i >= 0 is always true (because size_t is an unsigned type). You've written an infinite loop.

Doesn't your compiler warn you about that? I know g++ -Wextra does here.

What you can do instead is this:

for (size_t i = size; i--; ) {
    os << data[i];
}

This uses post-decrement to be able to check the old value of i, which allows the loop to stop just after i = 0 (at which point i has wrapped around to SIZE_MAX).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...