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