I'm trying to run my c++ program on an amazon linux ec2 instance and getting a segmentation fault in a piece of code that runs fine on MacOS and Ubuntu. The code excerpt is this
vector<unsigned char> header(8);
bool bool_byte[8];
unsigned char seg_byte;
int byte_num = 0;
for(int i = 0; i < 32; i++) {
bool_byte[i] = snb[i];
if(i % 8 == 7) {
seg_byte = to_byte(bool_byte);
byte_num = (i + 1)/8;
cout << "byte_num minus one is " << to_string(byte_num - 1) << endl;
cout << "vector size " << to_string(header.size()) << endl;
header[byte_num - 1] = seg_byte;
}
}
I'm converting a 32 bit boolean array to 4 bytes of type unsigned char. seg_byte
here may be '\\0', but even if I replace seg_byte
with 'a', or use header.reserve(8)
and use push_back
instead of an array index I still get the segmentation fault. I've also tried using vector<char>
and casting to char
and still get the segmentation fault. The cout
statements print this.
byte_num minus one is 0
vector size 8
byte_num minus one is 1
vector size 139991841770280
Segmentation fault
If I write a small test.cpp
file that only runs a for loop filling a vector<unsigned char>
I don't get any errors.
getting a segmentation fault in a piece of code that runs fine on MacOS and Ubuntu
If you build your program with Address Sanitizer (which you should get into the habit of doing all the time ), it will tell you right away about buffer overflows.
Building with Address Sanitizer is very easy:
g++ -fsanitize=address -g test.cpp
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.