Error with global string in multiple functions...

I declare a global string and give it a value "ABC" in Function1. When I try to cout it in my main function, it gives error:
Terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_S_construct null not valid

Code looks something like this...

1
2
3
4
5
6
7
8
9
10
11
12
string str;

void Function1()
{
	str = "ABC";
}

int main()
{
	Function1();
	cout << str;
}


The cout works perfectly fine within the 'Function1' function, but for some reason gives the error in main. I understand it has something to do with the difference between std::string and char*, but I don't know the exact problem. How do I avoid the error?
I understand it has something to do with the difference between std::string and char*
No, that code fragment should work just fine. And it does when I test it.
Code looks something like this...

Well, if it looks like that then it works perfectly well.

Perhaps you should show the actual code.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
using namespace std;

string str;

void Function1()
{
	str = "ABC";
}

int main()
{
	Function1();
	cout << str;
}


ABC



Let me guess - you followed the "gotta initialise all variables" brigade and actually wrote something like
string str = 0;
so trying to set your string to a null pointer.
Last edited on
Topic archived. No new replies allowed.