从string引起的串扰bug说起

972 篇文章 329 订阅
322 篇文章 11 订阅

         最近遇到一个低概率问题, 具体问题就不详细说了, 只简要说说: 拉取某接口失败(低概率), 做重复拉取一次的动作, 第二次成功, 但后台给客户端返回的值始终不对, 花了一番功夫, 才查出原因。 这个问题非常隐蔽, 来看看:

#include <iostream>
#include <stdio.h>
#include "curl.h"     // 请自己负责添加curl头文件和库
using namespace std;

static size_t downloadCallback(void *buffer, size_t sz, size_t nmemb, void *writer)
{
	string* psResponse = (string*) writer;
	size_t size = sz * nmemb;
	psResponse->append((char*) buffer, size);

	return sz * nmemb;
}

int main()
{
	string strUrl = "http://www.baidu.com";
	string strTmpStr = "xxxxxx";  // 假设这是第一次拉取失败时, 得到的响应

	//  第二次拉取
	CURL *curl = curl_easy_init();
	curl_easy_setopt(curl, CURLOPT_URL, strUrl.c_str());
	curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
	curl_easy_setopt(curl, CURLOPT_TIMEOUT, 2);
	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, downloadCallback); 
	curl_easy_setopt(curl, CURLOPT_WRITEDATA, &strTmpStr);   // 串扰,串扰,串扰!!!
	CURLcode res = curl_easy_perform(curl);
	curl_easy_cleanup(curl);
	string strRsp;
	if (res != CURLE_OK)
	{
		strRsp = "error";
	}
	else
	{
		strRsp = strTmpStr;
	}
	
	printf("strRsp is |%s|\n", strRsp.c_str());
	return 0;
}
      结果:
strRsp is |xxxxxx<!DOCTYPE html><!--STATUS OK-->
<html>
<head>
        <meta http-equiv="content-type" content="text/html;charset=utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=Edge">
        <link rel="dns-prefetch" href="//s1.bdstatic.com"/>
        <link rel="dns-prefetch" href="//t1.baidu.com"/>
        <link rel="dns-prefetch" href="//t2.baidu.com"/>
        <link rel="dns-prefetch" href="//t3.baidu.com"/>
        <link rel="dns-prefetch" href="//t10.baidu.com"/>
        <link rel="dns-prefetch" href="//t11.baidu.com"/>
        <link rel="dns-prefetch" href="//t12.baidu.com"/>
        <link rel="dns-prefetch" href="//b1.bdstatic.com"/>
        <title>百度一下,你就知道</title>
        <link href="http://s1.bdstatic.com/r/www/cache/stat..............................................(我省略了)


        看看, strTmpStr果然被串扰, 如果是在封装很多层的程序中, 串扰问题就比较难查了。 我遇到过很多类似的问题了, 如上问题的解决还算顺利。 解决办法也很简单, 使用前清空即可。


        不多说。



  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值