加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 内联函数的内存泄漏

发布时间:2020-12-16 09:38:23 所属栏目:百科 来源:网络整理
导读:我有一个内联函数定义如下: 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;} 当我使用内存泄漏工具检查
我有一个内联函数定义如下:

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

当我使用内存泄漏工具检查它时,它表示第1行(上面标记)是内存泄漏.
上面的代码有什么问题?

解决方法

我创建了完全可编译的示例:

#include <string>
#include <iostream>
#include <cstdio>

std::string Change( char * ) {
    std::string str;
    char temp[32] = "";

    sprintf(temp,temp[5]
    );

    str = temp;
    return str;
}

int main()
{
    char a[]={"abaaaaa2"};
    std::cout<<Change(a)<<std::endl;
}

在valgrind下运行时,我没有检测到泄漏:

==16829== 
==16829== HEAP SUMMARY:
==16829==     in use at exit: 0 bytes in 0 blocks
==16829==   total heap usage: 0 allocs,0 frees,0 bytes allocated
==16829== 
==16829== All heap blocks were freed -- no leaks are possible
==16829== 
==16829== For counts of detected and suppressed errors,rerun with: -v
==16829== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 15 from 8)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读