帮助内存泄漏 [英] Help with memory leaks

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

问题描述

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

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

推荐答案

这不是泄漏-这是一个悬而未决的参考.
That''s not a leak - that''s a hanging reference.
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.


函数Change()中没有内存泄漏

但是,在调用函数Change(char *指针)之前,请检查传递给函数Change()的char *是否指向动态分配的

而且您没有在整个函数中使用该char *指针,请确保该函数的逻辑正确性.

您可以使用std :: auto_ptr来避免内存泄漏.提升智能指针可能是更好的选择.

祝你好运. :)
There is no memory leak in function Change()

But check if the char* you passed to function Change() is pointing to dynamically allocated before calling function Change(char* pointer);

And you didn''t used that char *pointer in you whole function, make sure logical correctness of his function.

you can use std::auto_ptr for avoiding memory leak.Boost smart pointers could be better alternative.

Good luck. :)


函数Change()中没有内存泄漏

但是在调用函数Change(char *指针)之前,请检查传递给函数Change()的char *是否指向动态分配的对象.如果它是动态分配的,那么别忘了释放/删除它.

而且您没有在整个函数中使用该char *指针,请确保函数的逻辑正确性.

您可以使用std :: auto_ptr来避免内存泄漏.提升智能指针可能是更好的选择.

祝你好运. :)
There is no memory leak in function Change()

But check if the char* you passed to function Change() is pointing to dynamically allocated before calling function Change(char* pointer); if it is dynamically allocated then don''t forget to free/delete that.

And you didn''t used that char *pointer in you whole function, make sure logical correctness of your function.

you can use std::auto_ptr for avoiding memory leak.Boost smart pointers could be better alternative.

Good luck. :)


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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆