0

I found below shown piece of code on libcurl website, but I don't get the reason of setting first char to 0 errbuf[0] = 0; ? What about the others?

curl = curl_easy_init();
if(curl) {
  CURLcode res;

  char errbuf[CURL_ERROR_SIZE];

  curl_easy_setopt(curl, CURLOPT_URL, "https://example.com");

  /* provide a buffer to store errors in */
  curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errbuf);

  /* set the error buffer as empty before performing a request */
  errbuf[0] = 0;

  /* perform the request */
  res = curl_easy_perform(curl);

  /* if the request did not complete correctly, show the error
  information. if no detailed error information was written to errbuf
  show the more generic information from curl_easy_strerror instead.
  */
  if(res != CURLE_OK) {
    size_t len = strlen(errbuf);
    fprintf(stderr, "\nlibcurl: (%d) ", res);
    if(len)
      fprintf(stderr, "%s%s", errbuf,
              ((errbuf[len - 1] != '\n') ? "\n" : ""));
    else
      fprintf(stderr, "%s\n", curl_easy_strerror(res));
  }
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Anees
  • 49
  • 5
  • 3
    `errorbuf[0] = 0;` makes errorbuf what you would call "an empty string". It's a null-terminated string and it now begins with a null. curl will not read past this 0, so it does not matter what the other characters contain. – Drew Dormann Aug 09 '22 at 17:05
  • 1
    Setting only the first char to 0 is an optimization (only sets terminating 0 of a string), no need to initialize the rest of the buffer. (which could have been done using : `char errbuf[CURL_ERROR_SIZE]{};`) – Pepijn Kramer Aug 09 '22 at 17:09
  • @DrewDormann if not a duplicate at least an explanation. – Pepijn Kramer Aug 09 '22 at 17:10
  • 1
    All of the standard and most of the non-standard, character array-eating string handling functions expect the last character of relevance in the string to be followed by a null character, a 0, so that the function knows when to stop reading. There is no need to null any characters after the null because the reader has stopped reading and won't ever see them. – user4581301 Aug 09 '22 at 17:10
  • The code is using `CURLOPT_ERRORBUFFER` to have `curl_easy_perform()` write errors into `errbuf`. `errbuf[0] = 0;` is being used to initialize `errbuf` to an "empty" C-style string first so that `strlen(errbuf)` is always meaningful, even if no error is written to it. But, do note that since 7.60, libcurl will do that initialization for you, making this line of code redundant. – Remy Lebeau Aug 09 '22 at 17:19

0 Answers0