issue with huge strings

Hi everyone!

I have an issue when using huge strings. This is an example code :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//file main.cpp
#include <string>
#include <iostream>

const char* test()
{
    std::string output;
    for(size_t i = 0; i < 90000; i++)
    {
        output += "<xml>xmlxmlxmlxmlxmlxmlxmlxmlxmlxmlxmlxmlxmlxml</xml>";
    }
    return output.c_str();
}

int main()
{
    const char* output;
    output = test();
    std::cout << output << std::endl;
}


And this is the gdb output:

1
2
3
4
#0  strlen () at ../sysdeps/x86_64/strlen.S:106
#1  0x00007ffff7b64229 in std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*) ()
   from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#2  0x0000000000400c9b in main () at main.cpp:19 


Could some one please help me?

Thanks a lot!

All the best
Last edited on
The string goes out of scope at the end of the function so the pointer that is returned from c_str() will no longer be valid.
Your problem isn't the insanely large string -- that's just a matter of having enough memory on your computer.

Your problem is you're trying to return a pointer to an object that no longer exists. std::string output (see [1]) is a local variable, and is deallocated once your test function ends. I'm disappointed g++ doesn't warn about this even with all warnings on.

Just use std::strings if you're not sure what's going on.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

#include <iostream>
#include <string>

//const char* test()
std::string test()
{
    std::string output; // [1]
    for(size_t i = 0; i < 90000; i++)
    {
        output += "<xml>xmlxmlxmlxmlxmlxmlxmlxmlxmlxmlxmlxmlxmlxml</xml>";
    }
    return output;
}

int main()
{
    //const char* output;
    std::string output; // [2]
    output = test();
    std::cout << output << std::endl;
}
Last edited on
Topic archived. No new replies allowed.