0

I have a C++ program that takes as input some key and store it in a vector. The program is a legacy code so it uses scanf to take the input. And it first puts the input in a char[64] input array. Then it compares it to find a specific input and then adds it to the vector of string.

char[64] input;
vector<string> collection;

scanf("%s", input);

if(input == "some value"){
    collection.push_back(input);
}

Now I had a case where the input was more than 64 characters and was about 100 chars.

The program was behaving as expected and putting this long input in the vector until I switched to a new compiler gcc 10.

I noticed afterwards that the string being pushed back to collection is an empty string which caused undefined behavior later on in the program because I use the string in the vector to do some functionality.

I also noticed that when I build using the debug flag this problem disappears. i.e it takes the long string and put it in the vector as expected not an empty string.

I solved the issue by making the input char array of size 128 instead of 64 since I don't expected the input to have a larger number of chars than that but I was curious to know why this behavior happens on new compilers?

TTS
  • 19
  • 2
  • 4
    Writing past the end of an array has always been *undefined behavior*, it just accidentally happened to appear to work correctly on the previous compiler – UnholySheep Aug 14 '21 at 23:21
  • 2
    Also just increasing the buffer is still insufficient protection against buffer overflows. You should really use functionality that prevents that (such as specifying max field width in `scanf` or using `fgets`) – UnholySheep Aug 14 '21 at 23:25
  • 6
    _The program is a legacy code so it uses `scanf` to take the input._ I would fix that, personally. – Paul Sanders Aug 14 '21 at 23:29
  • 6
    `input == "some value"` is always `false`. – Yksisarvinen Aug 14 '21 at 23:54
  • 1
    *"I don't expected the input to have a larger number of chars than that"* -- this was probably also the justification used by whomever decided on the 64 character size... – JaMiT Aug 15 '21 at 00:52

0 Answers0