Take the 2-minute tour ×

I'm trying to download a test file from my server using the cURL library with this code:


#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(ptr, 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);


    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?

share|improve this question
add comment

2 Answers

up vote 2 down vote accepted

I'm not familiar with cURL, but two things that might help you, so forgive me if I speak nonsense:

  1. char *url = "http://pixhost.tk/test.txt"; is a read-only string, so change it to const char *url = "http://pixhost.tk/test.txt"; this might reveal your problem during compilation.
  2. 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.
share|improve this answer
I'm placing my bets on 2. –  a3nm May 1 '11 at 2:14
Me too, a3_nm. It looks like he is trying to open a directory for write. –  Zan Lynx May 1 '11 at 3:07
add comment

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.

share|improve this answer
add comment

Your Answer


