segfault using address sanitizer and multiple files, but works fine with a single file
The following example with malloc
works fine when the malloc is in the test file, but fails when the same code is split across multiple files.
Note that if I get rid of "#include <cmocka.h>" in the multi-file failing example, it works fine.
I'm building with -fsanitize=address
.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <setjmp.h>
#include <cmocka.h>
typedef struct foo {
int x;
} foo_t;
foo_t * bar() {
foo_t * c = NULL;
c = malloc(sizeof(foo_t));
return c;
}
static void test_bar() {
foo_t * c = bar();
free(c);
}
int main(void) {
test_bar();
}
When I split the same thing over 3 files "fail_test.c" "config.c" "config.h" I get a set a SEGV
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <setjmp.h>
#include <cmocka.h>
#include "config.h"
static void test_bar() {
foo_t * c = bar();
free(c);
}
int main(void) {
test_bar();
}
typedef struct foo {
int x;
} foo_t;
foo_t * bar();
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "config.h"
foo_t * bar()
{
foo_t * c = NULL;
c = malloc(sizeof(foo_t));
return c;
}
To reproduce, full build command is:
gcc -o "fail_test" "fail_test.c" "config.c" -DUNIT_TESTING -Wall -Wextra -g3 -fsanitize=address -fdiagnostics-color=always -lglib-2.0 -lX11 -lcmocka -I/usr/include -I/usr/include/glib-2.0/ -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/local/include -I/usr/lib/glib-2.0/include && "./fail_test"
or
gcc -o "pass_test" "pass_test.c" -DUNIT_TESTING -Wall -Wextra -g3 -fsanitize=address -fdiagnostics-color=always -lglib-2.0 -lX11 -lcmocka -I/usr/include -I/usr/include/glib-2.0/ -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/local/include -I/usr/lib/glib-2.0/include && "./pass_test"