使用valgrind检测内存使用是否有问题:$ valgrind --tool=memcheck --leak-check=full ./mem
下面是截取的一些命令输出片段:
==9763== Invalid read of size 1==9763== at 0x407FD6E: vfprintf (vfprintf.c:1620)==9763== by 0x408789F: printf (printf.c:35)==9763== by 0x80485DC: main (mem.c:26)==9763== Address 0x41a3068 is 0 bytes inside a block of size 128 free'd==9763== at 0x4025BF0: free (vg_replace_malloc.c:366)==9763== by 0x804857F: getUrl (mem.c:19)==9763== by 0x80485AF: main (mem.c:25)==9763== Invalid read of size 4==9763== at 0x80485ED: main (mem.c:28)==9763== Address 0x41a302c is 4 bytes inside a block of size 12 free'd==9763== at 0x4025BF0: free (vg_replace_malloc.c:366)==9763== by 0x80485E8: main (mem.c:27)==9763== HEAP SUMMARY:==9763== in use at exit: 0 bytes in 0 blocks==9763== total heap usage: 2 allocs, 2 frees, 140 bytes allocated==9763== ==9763== All heap blocks were freed -- no leaks are possible
”Address 0x41a302c is 4 bytes inside a block of size 12 free'd“这句话翻译过来大概就是说要访问的地址0x41a302c已经在被free掉的内存块中了。
”total heap usage: 2 allocs, 2 frees, 140bytes allocated“--line是128字节,sizeof(structurl)=12,所以一共是140字节,alloc了2次,free了2次,所以no leaks are possible。
我们把断点设在16、20、28行,来看一下free之后,指针存储的地址变了没,通过该指针还能否访问内存。

为了使26行”合法“运行,我们把19行注释掉。这时用valgrind工具又会检查出”可能“有内存泄漏--事实上也确实是有内存泄漏。

报告说alloc了2次,free了1次,可能在一个块里面有128 bytes的内存泄漏。
这line变量free也不是,不free也不是,肿么办
解决办法:
1 #include 2 #include 3 #include 4 5 struct url{ 6 char *domain; 7 char *path; 8 int depth; 9 };10 11 void freeUrl(struct url* rect){12 free(rect->domain);13 free(rect->path);14 free(rect);15 }16 17 void getUrl(struct url* rect){18 char *line;19 line=calloc(128,sizeof(char));20 strcpy(line,"http://www.baidu.com /gaoji/preferences.html 2");21 char *delim=" ";22 char *d=calloc(40,sizeof(char));23 char *p=calloc(80,sizeof(char));24 strcpy(d,strtok(line,delim));25 strcpy(p,strtok(NULL,delim));26 rect->domain=d;27 rect->path=p;28 rect->depth=atoi(strtok(NULL,delim));29 free(line);30 }31 32 main(){33 struct url* rect;34 rect=calloc(1,sizeof(struct url));35 printf("%d\n",sizeof(struct url));36 getUrl(rect);37 printf("|%s|%s|%d|\n",rect->domain,rect->path,rect->depth);38 freeUrl(rect);39 }
valgrind没有检查出任何问题:
