Luka
Luka

Reputation: 1801

Heap corruption in std::string?

My code fails with Heap corruption in std::string?

string unsigned_int_to_string(unsigned int in)
{
    using namespace boost::spirit;
    using boost::spirit::karma::generate;

    char x[65];
    char *p = x;
    generate(p, uint_, in);
    *p = '\0';

    return string(x);
}


void add(string &s, unsigned int in)
{
    string d = unsigned_int_to_string(in);
    s += d+":";
}

If I run my program on a windows 7 PC it works OK but it crashes in random places on a windows 8.1 PC. Why heap corruption, I simply don't understand? Is there any chance my RAM is failing or any other programs cause issues?

The corruption happens in at least 2 cases:

a) threadex.c (code too long to post)
b) free.c called by xstring (code as shown above, too long to post more)

Upvotes: 0

Views: 1588

Answers (2)

Zac Howland
Zac Howland

Reputation: 15872

First off, using boost::spirit::karma::generate to return a string does not require you to use a character buffer first:

std::string unsigned_int_to_string(unsigned int value)
{
    using namespace boost::spirit;
    using boost::spirit::karma::generate;
    std::string str;
    generate(std::back_inserter(str), uint_, value);
    return str;
}

What is likely happening: somewhere in your code, x (being an unintialized character array of a fixed size) is being accessed beyond its bounds. This would result in you trashing memory and after that anything can happen.

If that is not occurring, you are likely trashing memory in some other location of your code which is resulting in undefined behavior.

The long and the short of it: you are invoking undefined behavior somewhere in your code.

As an aside, if you are using a C++11-compliant compiler, std::to_string() already exists.

Upvotes: 3

StilesCrisis
StilesCrisis

Reputation: 16290

Your bug is somewhere else, not inside this function.

Most likely s and/or d are corrupt. Without seeing more code it's impossible to know why. If I had to guess, I'd think their memory has already been freed (for instance, if they are part of a class object and that class object is already deleted). Or perhaps another section of code is doing something wrong and overwriting their memory.

Upvotes: 2

Related Questions