Run time error C strings

replaceSubstring Function
Write a function named replaceSubstring. The function should accept three C-string or string object arguments. Let's call them string1, string2, and string3. It should search string1 for all occurrences of string2. When it finds an occurrence of string2, it should replace it with string3. For ex. suppose the three arguments have the following values:
string 1: "the dog jumped over the fence."
string 2: "the"
string 3: "that"
With these three argument, the function would return a string object with the value "that dog jumped over that fence." Demonstrate the function in a complete program.

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#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";
	char str3[SIZE] = "that";

	replace_substring(str1, str2, str3);
	return 0;
}

void replace_substring(char * string1, char *string2, char *string3)
{
	char *strPtr = nullptr;

	bool loop_exit(false);
//everything commented in the loop is statements to help me see what was //executing
	for (int outer = 0; loop_exit != true; outer++)
	{
		//std::cout << "Outer " << outer << "\n";
		strPtr = strstr(string1, string2);
		if (strPtr == nullptr)
		{
			//std::cout << "Bow wow\n";
			loop_exit = true;
		}
		
		for (int count = 0; count < strlen(string3); count++)
		{
			strPtr[count] = string3[count];
			//std::cout << "Inner " << count << "\n";
			//std::cout << strPtr << "\n";
		}
		
	}
	//std::cout << "Loop exited.\n";
	std::cout << strPtr;
}

When I run this program it crashes. I used the statements in the loops to see if that would show me what is executing and what is not, in order to see how far the program was getting before crashing. Without the commented statements the program crashes but this is the output with them included.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Outer 0
Inner 0
the dog jumped over the fence
Inner 1
the dog jumped over the fence
Inner 2
tha dog jumped over the fence
Inner 3
thatdog jumped over the fence
Outer 1
Inner 0
the fence
Inner 1
the fence
Inner 2
tha fence
Inner 3
thatfence
Outer 2
Bow wow
Press any key to continue . . .//I have to press 'x' on the crash error window //for it to say press any key to continue. 

I am wondering if there is something wrong with using a bool as a loop condition but it seems to have executed so I'm not sure where the problem is.
Line 28: it checks if strPtr is null and sets loop_exit to true. Loop will be finished as soon as current iteration ends (when execution reaches line 40). Then on line 35 you do the copy even if pointer is null.
Topic archived. No new replies allowed.