开发者

C++ Allocated Memory Problem

开发者 https://www.devze.com 2023-01-24 20:28 出处:网络
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

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开发者_如何学Go 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? i.e. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消