[Solved] c++ Array MEMMOVE bug


In your memmove call, you are using the incorrect length:

memmove(s1+i+1,s1+i,strlen(s1));

strlen(s1) is the length of the string starting from the beginning and not including the null terminator. So there are two problems. First, you want the length of the string starting from the current position. Second, you want the length including the null terminator, so that the null terminator gets copied.

The result of these bugs is that if the first character is a vowel then the memove will over-write the null terminator and additional garbage in the buffer will start being processed as if it were part of your string.

Additionally memove will access outside the buffer given certain input and garbage in the buffer.

The solution is to use the correct length, strlen(s1+i), and to include the null terminator:

memmove(s1+i+1,s1+i,strlen(s1+i)+1);

cin.get(s1, 255) does store a null terminator, and in fact you can safely give it the correct buffer size: cin.get(s1, 256).


using std::string you can avoid these sorts of mistakes:

#include <cstring>
#include <string>
#include <iostream>

int main() {
    std::string s1;
    std::getline(std::cin, s1);

    for (int i = 0; i < s1.size(); ++i) {
        if (std::strchr("aeiou", s1[i])) {
            s1.insert(i, "p");
            ++i;
        }
    }
    std::cout << s1 << '\n';
}

Note that this doesn’t have any fixed buffer size, doesn’t have to give special consideration to null terminators, doesn’t have to figure out how many bytes need moving, and directly expresses the intent to “insert ‘p’ at this location”.

3

solved c++ Array MEMMOVE bug