Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c libcurl CURLOPT_POSTFIELDS奇怪错误_C - Fatal编程技术网

c libcurl CURLOPT_POSTFIELDS奇怪错误

c libcurl CURLOPT_POSTFIELDS奇怪错误,c,C,我是一个全新的c开发人员,在使用libcurl时遇到了一些问题。我以前在网上搜索了很多,但没有找到适合我的答案 这是纯c语言,没有++ 我有这个代码,请求失败了 char * write_url(MyData data) { char *field = malloc(20 * sizeof(char)); if (strcmp(data.sensorName,"Temperature")==0){ sprintf(field,"&temperature=%.2f",

我是一个全新的c开发人员,在使用libcurl时遇到了一些问题。我以前在网上搜索了很多,但没有找到适合我的答案

这是纯c语言,没有++

我有这个代码,请求失败了

char * write_url(MyData data)
{
  char *field = malloc(20 * sizeof(char));

  if (strcmp(data.sensorName,"Temperature")==0){
      sprintf(field,"&temperature=%.2f",data.measure);
   }

  CURL *curl;
  curl_global_init(CURL_GLOBAL_ALL);
  curl = curl_easy_init();
  curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  curl_easy_setopt(curl, CURLOPT_URL, "http://127.0.0.1/");
  curl_easy_setopt(curl, CURLOPT_POST, 1);

  curl_easy_setopt(curl, CURLOPT_POSTFIELDS, field);
  curl_easy_perform(curl);
  curl_easy_cleanup(curl);
}
但如果我改变

  curl_easy_setopt(curl, CURLOPT_POSTFIELDS, field);
为了

它起作用了。 但是我想通过这个函数传递数据

谢谢

malloc()不会初始化内存,因此您必须这样做。但是如果不使用if语句,内存将保持未初始化状态。在代码的else部分执行此操作:

if (strcmp(data.sensorName,"Temperature")==0)
{
     sprintf(field,"&temperature=%.2f",data.measure);
}
else
{
    strcmp(field,"Unknown") ;
}
并在完成后释放内存:

free(field) ;
还要注意,libcurl调用总是返回一个错误值,请使用它

curl = curl_easy_init();    //no error checking is perform in your code
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
curl_easy_setopt(curl, CURLOPT_URL, "http://127.0.0.1/");
curl_easy_setopt(curl, CURLOPT_POST, 1);

尝试在if后打印变量
字段
。它的内容是什么?如果if中的条件不正确,会发生什么情况?然后,
字段
未初始化。您应该至少使用空字符串对其进行初始化。如果strcmp失败,则未初始化字段,从而导致未定义的行为。
curl = curl_easy_init();    //no error checking is perform in your code
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
curl_easy_setopt(curl, CURLOPT_URL, "http://127.0.0.1/");
curl_easy_setopt(curl, CURLOPT_POST, 1);