https://gcc.gnu.org/bugzilla/show_bug.cgi?id=70262
Bug ID: 70262
Summary: Segmentation fault with large stack array, no fault
when alloca the same size
Product: gcc
Version: 5.3.1
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c
Assignee: unassigned at gcc dot gnu.org
Reporter: nickdu at msn dot com
Target Milestone: ---
I just ran into a segmentation fault in a binary I created with the gcc
compiler. The code is written in c. The problem appears to be with a stack
allocated buffer. The buffer is large, 1024 * 1024 chars. I realize that
there are some limitations on the stack size, though I think I'm still under
the limits. The strange thing is that when I changed to using alloca(1024 *
1024) the segmentation fault no longer occurs. My project consists of a bunch
of code and I have not yet attempted to pare it down to the bare minimum. I
will attempt to give you as much information as I can with respect to the
function in question.
The signature of the function is:
void log_event(int level, const char* format, ...)
The lines of code in question are:
// INFO and more critical we send to HTTP endpoint.
if ((level <= LOG_LEVEL_INFO) && (write_log_pipe != -1))
{
// Generate json for event.
char json[1024 * 1024];
// char* json = alloca(1024 * 1024);
unsigned int len = 1024 * 1024;
// generate_json(&ts, host_name, level_string, message,
// json, &len);
strcpy(json, "hello, world");
len = strlen(json);
printf("log_event(), len = %d, json = %s\n", len, json);
if (len < 1024 * 1024)
{
// Write json event to log pipe.
if (pthread_mutex_lock(&log_pipe_lock) == 0)
{
write(write_log_pipe, &len, sizeof(len));
write(write_log_pipe, json, len);
pthread_mutex_unlock(&log_pipe_lock);
}
}
}
As you can see I was playing around with commenting out pieces of code. Ignore
the commented function generate_json(). The code as it is above will generate
a segmentation fault. If I comment out the 1024 * 1024 char array and
uncomment the alloca the segmentation fault goes away.
Thanks,
Nick