I was working on other project and found, for me, strange behaviour from strdup.
Lets say we have 3 simple files:
foo.h:
#define FOO_H
void example(char *a);
#endif //FOO_H
foo.c:
#include <stdio.h>
#include <stdlib.h>
#include "foo.h"
void example(char *a) {
if (a == NULL) {
fprintf(stderr, "a is NULL");
exit(1);
}
char *temp = strdup(a);
printf("%s", temp);
}
bar.c
#include <stdio.h>
#include <stdlib.h>
#include "foo.h"
int main() {
char *a = "Hello Worldn";
example(a);
return 0;
}
When I compile these, I get warning and when I run these, I get seg fault:
*foo.c:10:18: warning: implicit declaration of function ‘strdup’ [-Wimplicit-function-declaration]
foo.c:10:18: warning: initialization of ‘char ’ from ‘int’ makes pointer from integer without a cast [-Wint-conversion]
The solution is to not compile with c11 or put your own strdup declaration in the .h file.
So the question is, why is this happening.