我正在用数组和指针编写程序,并得到了这个分段错误。有谁能解释一下为什么我在这段代码中出现了这个分段错误。
我的守则:
#include <stdio.h>
#include <curl/curl.h>
#include <string.h>
int main(void)
{
CURL *curl;
CURLcode res;
struct curl_slist *headers = NULL;
char CPID[50] = "98f5b52a59aa4503999894c10bc33dca" ;
char Uni_ID[10] = "Demo123" ;
char *postData;
curl = curl_easy_init();
if(curl)
{
curl_easy_setopt(curl, CURLOPT_URL, "https://avnetagent.iotconnect.io/api/2.0/agent/sync");
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
//postData = "{\"cpId\":\""+CPID+"\",\"uniqueId\":\""+Uni_ID+"\",\"option\":{\"attribute\":false,\"setting\":false,\"protocol\":false,\"device\":false,\"sdkConfig\":false,\"rule\":false}}";
postData = "{\"cpId\":\"";
strcat(postData,CPID);
strcat(postData,"\",\"uniqueId\":\"");
strcat(postData,Uni_ID);
strcat(postData,"\",\"option\":{\"attribute\":false,\"setting\":false,\"protocol\":false,\"device\":false,\"sdkConfig\":false,\"rule\":false}}");
headers = curl_slist_append(headers, "Accept: application/json");
headers = curl_slist_append(headers, "Content-Type: application/json");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postData);
/* Perform the request, res will get the return code */
res = curl_easy_perform(curl);
/* Check for errors */
if(res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
/* always cleanup */
curl_easy_cleanup(curl);
}
return 0;
}发布于 2020-07-29 08:06:15
你写的是你不允许修改的记忆,2)写到不属于你的内存。
这里
postData = "{\"cpId\":\"";将指针postData设置为指向字符串文本,即不允许修改的常量字符串。但是,你知道
strcat(postData,CPID);它将将字符串CPID附加到字符串文本。换句话说,它将通过覆盖字符串终止字符来修改字符串文本,而且它将在字符串文本之后将部分CPID复制到内存中。这两个操作都无效。
您需要的是使postData指向可以修改的内存。
图1:
char *postData; ---> char postData[8192];
postData = "{\"cpId\":\""; ---> strcpy(postData, "{\"cpId\":\"");图2:
char *postData; ---> char *postData = malloc(8192);
assert(postData != NULL);
postData = "{\"cpId\":\""; ---> strcpy(postData, "{\"cpId\":\"");
return 0; ---> free(postData);
return 0;这两个修复程序的缺点是内存大小固定(即8192个字符)。对于您想要发布的数据,这始终是足够的内存吗?
如果您知道上限,您可以设置一个固定的大小(就像我做的那样)。
如果您不知道上限,则必须更改代码,以便在运行时增加分配的内存,例如使用realloc (只适用于"Fix 2")。
请注意,使用"Fix 1“具有非常高的内存,例如,在大多数系统中,char postData[8192000];是一个问题,因为它们对具有自动存储持续时间的变量有一个大小限制。
因此,结论是:
如果您知道数据发布和的上限是合理的,那么可以使用简单的Fix 1。
否则我会推荐fix 2。
发布于 2020-07-29 06:49:41
问题就在
strcat(postData,CPID);postData所指向的内存既不可修改,也没有足够的空间容纳连接字符串。
你需要
string.
malloc()和
postData数组的维数足以容纳级联的postData足够的内存,并将指针存储在postData.中。
char *strcat(char *dest, const char *src);
strcat()函数将src字符串附加到dest字符串,覆盖dest__末尾的终止空字节,然后添加一个终止空字节。字符串可能不重叠,而且dest字符串必须有足够的空间,因为result.If dest不够大,程序行为不可预测;.
https://stackoverflow.com/questions/63147794
复制相似问题