C++分配内存问题

标签 c++ python memory-management ctypes

我已经很久没有用C++编程了,但是我最近写了一个C++函数,遇到了一些麻烦。该函数返回一个结构 Result,其中包含一些字符串。我以为我为字符串分配了内存,但 jsonResult 有时会被部分覆盖。

    //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;

其他信息: 我正在使用 ctypes 观察我编写的 python 绑定(bind)背后的所有这些。不过,不要认为这真的会产生任何影响。

最佳答案

使用std::string。你不会后悔的。

关于C++分配内存问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4139576/

相关文章:

c++ - 删除数组指针

python - 循环列表时的累积加法

iphone - 在 CocoaTouch (iPhone OS) 中,如何查找/消除 Instruments Leak 工具未找到的泄漏?

c++ - 删除传递给类的指针 vector

带有外部 SDK 的 C++ Diamond of Doom

c++ - zlib 压缩/解压缩 C++ Linux

c++ - 在 copy-and-swap 习语中实现交换

python - 导入错误 : No module named azure. storage.blob

python - 无法关闭 gtk 对话窗口

memory-management - 为什么即使内存不足且有足够的可用OS内存,JVM也会突然不分配最大的堆设置?