Why is this '\n' causing a run time error?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <cstring>

void replace_substring(char *, char *, char *);

int main()
{

	const int 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.
As Zhuge said. See for yourself:
1
2
3
4
5
6
7
8
void replace_substring(char * string1, char *string2, char *string3)
{
    char *strPtr = nullptr;

    strPtr = strstr(string1, string2);
    if (!strPtr) std::cerr << "Null Pointer detected!";
    //std::cout << strPtr;
}
Topic archived. No new replies allowed.