Segmentation Fault Using cURL
I'm trying to download a test file from my server using the cURL library with this code:
#define CURL_STATICLIB
#include <stdio.h>
#include <curl/curl.h>
#include <curl/types.h>
#include <curl/easy.h>
#include <string.h>
size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream)
{
size_t written;
written = fwrite(pt开发者_Python百科r, size, nmemb, stream);
return written;
}
int main(void)
{
CURL *curl;
FILE *fp;
CURLcode res;
char *url = "http://pixhost.tk/test.txt";
char outfilename[FILENAME_MAX] = "/Users/Nathan/Desktop";
curl = curl_easy_init();
if (curl)
{
fp = fopen(outfilename, "wb");
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
fclose(fp);
}
return 0;
}
And compiling it like this:
$ gcc main.c -lcurl -o curltest
But when I execute it I'm getting a Segmentation Fault error. What should I do to correct this?
I'm not familiar with cURL, but two things that might help you, so forgive me if I speak nonsense:
char *url = "http://pixhost.tk/test.txt";
is a read-only string, so change it toconst char *url = "http://pixhost.tk/test.txt";
this might reveal your problem during compilation.- You don't check for the result of
fopen
, maybe it failed, which explains the segfault, and it is seems likely to me since you try to open "/Users/Nathan/Desktop" which should be a directory AFAIK.
It's been a while since I worked with curl, and I'm not sure this would cause a segfault, I think you should be calling fwrite like this:
fwrite(ptr, 1, nmemb * size, stream);
Because fwrite returns the number of elements written, and size
is not (I don't think) guaranteed to be one. And since you're returning what fwrite returns, I believe you're returning less bytes than you're actually writing, since the function is supposed to return how many bytes it wrote.
精彩评论