内存管理以及调试工具

 

1.gdb 好工具

参考gdb使用方法介绍

2.valgrind工具:可以查看内存使用情况,

用法:valgrind file.o

precondition: 使用gcc  -g   file.c -o file.o 编译

3.二级指针技巧

在调用二级指针的主函数里 free 二级指针的内容,二级指针在作为参数的函数里初始化。这样才不会浪费内存。

#include <stdio.h>
#include <malloc.h>
#include <string.h>
void test(char **p)
{
    *p = (char*)malloc(10 * sizeof(char));
    strcpy(*p, "123456789" );   
}
void main()
{
    char **str = NULL ; //原代码:char *str = NULL;
    test(str);          //       test(&str);
    printf("%s\n", str);
    free(str);
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章