csegmentation-faultwarningsstrdup

strdup giving weird warning and Segmentation fault


I was working on other project and found, for me, strange behaviour from strdup.

Lets say we have 3 simple files:

foo.h:

#ifndef 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 World\n";
    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.


Solution

  • The solution is to not compile with c11 or put your own strdup declaration in the .h file.

    No, the solution is to include string.h for strdup(). About the error messages, see: Implicit function declarations in C and Are prototypes required for all functions in C89, C90 or C99?.

    Also note that strdup() allocates memory dynamically with malloc() which needs to be deallocated. You're missing a call to free() in your code.

    Additionally, it returns a null pointer if it failed to allocate memory, in which case temp would hold a null pointer, and the subsequent call to printf() would invoke undefined behavior.