简体   繁体   中英

C++ Allocated Memory Problem

It has been a long time since I have programmed in C++, but I recently wrote a little C++ function and am having a little bit of trouble. The function returns a struct, Result, that have some strings in it. I thought I allocated memory for the strings, but jsonResult is sometimes partially overwritten.

    //The structs
    struct Interp {
         int score;
         char* sentence;
         char* jsonResult;
    };

    struct Result {
         int resultCode;
         char* errorMessage;
         Interp interp;
    };

...

    //Inside the function
    Result result;

    //Store decode
    const char* jsonResult,* sentence;
    if (result.resultCode == -1)
    {
            LVInterpretation interp = port.GetInterpretation(voiceChannel, 0);

            result.interp.score = interp.Score();
            sentence = interp.InputSentence();
            jsonResult = interp.ResultData().Print(SI_FORMAT_ECMA);
    }

    //Allocate memory for strings
    result.interp.jsonResult = new char[strlen(jsonResult) + 1];
    strcpy(result.interp.jsonResult, jsonResult);

    result.interp.sentence = new char[strlen(sentence) + 1];
    strcpy(result.interp.sentence, sentence);

    result.errorMessage = new char[strlen(errorMessage) + 1];
    strcpy(result.errorMessage, errorMessage);

    return result;

Other info: I am observing all of this behind the python binding that I wrote, using ctypes. Don't think that is really effecting anything though.

Use std::string . You won't regret it.

I'd put money on your problem being in here:

jsonResult = interp.ResultData().Print(SI_FORMAT_ECMA);

Who 'owns' the char* array returned by Print()? Maybe it's attempting to return a pointer to memory that's out of scope???

example:

  char* badFunction(void)
  {
     char test[100];
     strcpy(test,"This is really clever"); // oh, yeah?
     return test; // returns pointer to data that's out of scope
  }

One other thing. Assign null pointers to sentence, jsonResult, etc when you declare them. Otherwise you could end up strcpy()ing uninitialized data,

Couple of things:

  1. What does "partially overwritten" mean? How do you know this? ie what is your expected output vs. what you see?

  2. It's not really clear how result.resultCode is set to -1 (or if it is at all), and if it is set, how does the memory get allocated in interp.InputSentence() and interp.ResultData().Print(SI_FORMAT_ECMA) ? I'd suggest that your problem lies there

The rest of the code should work as long as jsonResult and sentence contain valid null terminated strings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM