Created
March 18, 2014 13:34
-
-
Save emilisto/9620134 to your computer and use it in GitHub Desktop.
C99 problem with strdup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* $ gcc -std=c99 -o segfault segfault.c -lpthread | |
* segfault.c: In function ‘thread_fn’: | |
* segfault.c:7:5: warning: implicit declaration of function ‘strdup’ [-Wimplicit-function-declaration] | |
* segfault.c:7:17: warning: initialization makes pointer from integer without a cast [enabled by default] | |
* $ ./segfault | |
* Segmentation fault | |
*/ | |
#include <stdio.h> | |
#include <string.h> | |
#include <pthread.h> | |
static void *thread_fn(void *arg) | |
{ | |
char *str = strdup("a string literal"); | |
printf("here's a string: %s\n", str); | |
} | |
int main() | |
{ | |
pthread_t thread; | |
pthread_create(&thread, NULL, thread_fn, NULL); | |
pthread_join(thread, NULL); | |
return 0; | |
} |
Another solution is to use the GNU99 option of GCC, i.e. compile with -std=gnu99
I came here by searching "strdup c99".
One of the solutions is to append
-D_GNU_SOURCE
to the gcc command line or prepending#define _GNU_SOURCE
to the beginning of the file.
Faced a similar problem.
This solved my issue.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I came here by searching "strdup c99".
One of the solutions is to append
-D_GNU_SOURCE
to the gcc command line or prepending#define _GNU_SOURCE
to the beginning of the file.