#include <iostream>
#include <cstring>
void replace_substring(char *, char *, char *);
int main()
{
constint SIZE = 50;
char str1[SIZE] = "the dog jumped over the fence";
char str2[SIZE] = "the\n";//Here is the '\n' that is causing problems
char str3[SIZE] = "that";
replace_substring(str1, str2, str3);
return 0;
}
void replace_substring(char * string1, char *string2, char *string3)
{
char *strPtr = nullptr;
strPtr = strstr(string1, string2);
std::cout << strPtr;
}
Here is the program, the '\n' char is what is causing the program to crash, when I remove it the program prints fine. Obviously I know what the problem is but I'm not sure why it does this? What is going on behind the computer that the newline char is causing the program to crash?
I'd guess it is crashing because it is looking for "the\n" inside of "the dog jumped over the fence"; this fails, so strstr() returns nullptr. Then you try to print that string to standard output on 24, which crashes as it tries to dereference that null pointer.