3

I have the following code, which is my attempt to make a single string containing the stored HTTP header fields:

typedef struct _header {
    char* name;
    char* value;
} header;

const header headers[] = {
    { "Content-Type", "text/html" },
    { "Server", "testServer" }
};

int headerStringSize = sizeof(char) * 1024 + 1;
char* headerString = malloc(headerStringSize);
int i, headersLength = sizeof(headers) / sizeof(headers[0]);
for (i = 0; i < headersLength; ++i) {
    header h = headers[i];
    snprintf(headerString, headerStringSize, "%s: %s\r\n", h.name, h.value);
}

However, it doesn't work as snprintf simply overwrites the contents of headerString on each iteration, rather than appending at the correct char index. I am used to higher-level languages than C, so my problems are entirely down to my own ignorance. I would, therefore, greatly appreciate it if someone could show me the best way to achieve what I want.

5
  • Your variable names are confusing .
    – ameyCU
    Commented Oct 3, 2015 at 12:13
  • You might like to have look at strcpy() and strcat().
    – alk
    Commented Oct 3, 2015 at 12:14
  • 1
    headerString[0]=0;before the loop and snprintf(headerString + strlen(headerString), .... in the loop.
    – mch
    Commented Oct 3, 2015 at 12:14
  • @ameyCU Okay, feel free to tell me how I could name them better.
    – user162097
    Commented Oct 3, 2015 at 12:14
  • @mch Thank you very much, that's the fix I needed! Even though it's only short, feel free to write it as an answer so that I can accept it.
    – user162097
    Commented Oct 3, 2015 at 12:17

1 Answer 1

4

You should initialize your string:

headerString[0]=0;

before the loop.

Now you can calculate the end of the string and give snprintf a pointer to the end of the string:

snprintf(headerString + strlen(headerString), headerStringSize - strlen(headerString), "%s: %s\r\n", h.name, h.value);

Also note the changed maximum length parameter. You should also add a check on the return value of malloc.

3
  • There is no buffer overflow protection with this code. Because the second argument of snprintf is unsigned so if strlen(headerString) > headerStringSize then headerStringSize - strlen(headerString) will underflow and be cast to a big unsigned number. In this case snprintf will happily create a buffer overflow. Commented Dec 14, 2016 at 17:33
  • @leszek.hanusz if you do only this, your szenario cannot happen, the maximum value of strlen(headerString) is headerStringSize - 1, in this case the snprintf will not do anything.
    – mch
    Commented Dec 14, 2016 at 18:22
  • indeed, a buffer overflow in this case can only happen if there was already another buffer overflow before... Commented Dec 14, 2016 at 18:44

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.