1. fread函数需要注意的点
bool ip_arrival(string ip) {
FILE *pfd = NULL;
unsigned char tmpbuf[1024];
//memset(tmpbuf, '\0', sizeof(tmpbuf));
//Block ping
int maxnaps = 10;
int fread_num = 0;
while (maxnaps-- > 0) {
string cmd = string("ping -c1 ") + ip;
pfd = popen(cmd.c_str(), "r");
if (pfd == NULL) {
WFD_SINK_LOG(" popen failed\n");
return false;
}
if( (fread_num = fread(tmpbuf, 1, sizeof(tmpbuf), pfd)) <= 0) {
pclose(pfd);
return false;
}
WFD_SINK_LOG("\ntmpbuf: %s\n", tmpbuf);
if(strstr((const char *)&tmpbuf, "bytes from") ) {
pclose(pfd);
return true;
}
pclose(pfd);
WFD_SINK_LOG("maxnaps: %d\n", maxnaps);
}
WFD_SINK_LOG("the ip: %s can not arrive\n", ip.c_str());
return false;
}
从上面的代码可以看出fread有可能出问题,因为tmpbuf没有'\0'结尾,
需要补上,tmpbuf[fread_num] = '\0'; 这个!
第二:为什么delete p;后最好加上p = NULL; ? (浅谈内存泄露和内存过度释放)
在释放内存后,要将相关指针置为NULL. 这样可以防止后续对该指针进行操作时出错, 先看一个不好的风格.该程序风格不好(尽管正确):
现在假设程序很大,不小心又释放了一次,即:
运行程序,程序会crash, 这就是内存过度释放的后果, 如果程序很大,就很不好找. 而且,编译器提示的信息也非常有限。来看看下面的程序,在释放后将指针置为NULL:
结果程序可以正常运行,这就是将p置为NULL的好处。
事实上,在下面的程序可以看出问题:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char *p = NULL;
p = (char * )malloc( 4 * sizeof( char ) );
free(p);
strcpy( p, "abc" );
printf( "%s\n", p );
return 0;
}
可以正常打印,这里就出现了大家常见的“悬空指针”,
下面的例子也是:
void *p;
p=malloc(10);//......
free(p);
正确的做法是:需要将p = null,不然出错误!这样的错误经常出现!
第三:调用fclose之后,FILE *fp会变成NULL吗?不会,没有什么机制把fp置空的动作,只是这个时候fp所指向的区域已经不再有效。