Reputation: 21
I am working on a simple web server in C, and whenever I try to write to a char[] that I have declared in main in another function, I am getting a segfault. Before anyone suggests, I have not declared it as a string literal. I have tried allocating with malloc(), setting every char in the array to the null terminator on initialization, and not initializing it to anything (i.e. it is not read until something new is written to it, so there is not a reason to zero it to anything initially), all to no avail.
The syntax of what is going on is as follows:
#define MAX_BUFFER_LENGTH 20
int some_function(char *buffer) { //many other params as well
//lots of other code
snprintf(buffer, MAX_BUFFER_LENGTH, "%s", "HTTP/1.0 404 Not Found"); // This is where the segfault is thrown
}
int main(int argc, char *argv[]) {
char buffer[MAX_BUFFER_LENGTH];
//many other declarations
//...
some_function(buffer);
}
The odd thing is, is the segfault only occurs the first time that I call the write to the buffer with a specific syntax. There are some requests that do not create a segfault. If I submit the requests that cause the segfault after the ones that do not, they no longer cause a segfault. Any insight?
Upvotes: 0
Views: 290
Reputation: 223972
Your buffer is not an array of characters. It's an array of character pointers. Your compiler should have warned you about the type mismatch.
Change the declaration to:
char buffer[MAX_BUFFER_LENGTH];
Upvotes: 3