cout prevents the program from crashing?

Hello.

Look at here

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
int main()
{
	std::vector<string> result;
	char delim = ',';
	int lastPos = 0;
	string my = "Hello,I,Am,Michael";

	int tpos;

	do
	{
		//cout << "# EXECUTED #" << endl;

		tpos = my.find(delim, lastPos);
		result.push_back(my.substr(lastPos, tpos));

		lastPos = tpos;
	} while (tpos != -1);

	cout << endl << endl << endl << endl;

	for (int i = 0; i < result.size(); i++)	
		cout << result[i] << endl;
		
	return 0;
}


This code generates a bad_alloc exception.

But if I un-comment the cout inside the do-while loop it "works"

(clearly, the code isn't any good, it's just an example)


Am I in front of an UB?
Last edited on
What do you mean by "works"?

On my machine the program seems to go into an infinite loop.

Why are you trying to use find() and substr() to parse this string instead of using a stringsream?

The program without the cout statement causes a crash: screenshot here -> http://prntscr.com/b9keq5

When I put the cout, I can see the infinite loop.

Why are you trying to use find() and substr() to parse this string instead of using a stringsream?


It's just a test, trash code.
You should see the same problem with or without the cout if you wait long enough. Remember cout is very slow, so it may take some time but you should get the same out of memory exception if you wait long enough.
you should get the same out of memory exception if you wait long enough.


I have the program running for 2-3 minutes and nothing happens!
That still may not be long enough. Depending on how much memory your system has and the processor speed it could take much longer, I would guess at a figure in the tens of minutes.

Your program still has the infinite loop and you are still inserting the string into your vector, so it will still crash, sometime.




> screenshot here
useless. Provide a backtrace.


1
2
3
int tpos;
tpos = my.find(delim, lastPos);
while (tpos != -1);

http://www.cplusplus.com/reference/string/string/find/
`string::find()' returns a size_t, not an int
and it returns string::npos if there are not matches, no -1

So stop aiming at your foot.
`string::find()' returns a size_t, not an int
and it returns string::npos if there are not matches, no -1
So stop aiming at your foot.


I already pointed out it's not a code i'm working on, it's just trash and mustn't be taken seriously.

That still may not be long enough. Depending on how much memory your system has and the processor speed it could take much longer, I would guess at a figure in the tens of minutes.

Your program still has the infinite loop and you are still inserting the string into your vector, so it will still crash, sometime.


It's really weird.

Without the cout the program immediately crashes. With it, I have reached about 1.000.000 while-loop execution and still doesn't crash!
Topic archived. No new replies allowed.