那些年,踩过的坑

 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. 这样可以防止后续对该指针进行操作时出错, 先看一个不好的风格.该程序风格不好(尽管正确):

[cpp]  view plain  copy
  1. #include<stdio.h>
  2. int main()  
  3. {  
  4.     int *p = new int(5);  
  5.     delete p;  
  6.     return 0;  
  7. }  

现在假设程序很大,不小心又释放了一次,即:

[cpp]  view plain  copy
  1. #include<stdio.h>  
  2. int main()  
  3. {  
  4.     int *p = new int(5);  
  5.     delete p;  
  6.     delete p;  
  7.     return 0;  
  8. }  

       运行程序,程序会crash, 这就是内存过度释放的后果, 如果程序很大,就很不好找. 而且,编译器提示的信息也非常有限。来看看下面的程序,在释放后将指针置为NULL:

[cpp]  view plain  copy
  1. #include<stdio.h>  
  2. int main()  
  3. {  
  4.     int *p = new int(5);  
  5.     delete p;  
  6.     p = NULL; // 如果没有这一个语句,程序就会crash  
  7.     delete p; // 没关系, 但通常会对是否为NULL进行判断, 这样就更需要将p置为NULL了  
  8.     p = NULL;
  9.     return 0;  
  10. }  

        结果程序可以正常运行,这就是将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所指向的区域已经不再有效。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值