Skip to content

Instantly share code, notes, and snippets.

@emilisto
Created March 18, 2014 13:34
Show Gist options
  • Save emilisto/9620134 to your computer and use it in GitHub Desktop.
Save emilisto/9620134 to your computer and use it in GitHub Desktop.
C99 problem with strdup
/*
* $ 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;
}
@YtvwlD
Copy link

YtvwlD commented Aug 29, 2017

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.

@sgsfak
Copy link

sgsfak commented Jun 6, 2018

Another solution is to use the GNU99 option of GCC, i.e. compile with -std=gnu99

@yashasvi-goel
Copy link

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