帮助内存泄漏

扫码查看
本文介绍了帮助内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现代码的某些部分是泄漏内存.请帮助我解决此问题:

I found that in the parts of the code is leak memory. Please help me fix this:

inline string Change(char *pointer) {
    string str;
    char temp[32] = "";

    sprintf(temp,"%c:%c:%c:%c:%c:%c", //line 1
        temp[0],temp[1],temp[2],
        temp[3],temp[4],temp[5],
    );

    str = temp;
    return str;
}

推荐答案

char temp[32] = "";

在堆栈上创建一个由32个字符组成的数组.

Creates an array of 32 characters on the stack.

str = temp;
return str;

返回指向数组的指针.
好的,这是内联代码,但是当您退出该例程时,它仍然是您正在使用的堆栈引用.如果在构造该字符串的例程之外引用该字符串,则它指向未使用或正在由其他函数使用的内存.始终从堆而不是堆栈中分配此类数据.

Returns the pointer to the array.
Ok, this is inline code, but when you exit that routine it is still a stack reference you are using. If you refer to that string outside the routine in which it was constructed, then it points to memory that is either unused, or is in use by a different function. Always allocate such data from the heap - not the stack.




这篇关于帮助内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 08:05
查看更多