strdup not in string.h?

strdup not in string.h?

by Emmanuel Lazard -
Number of replies: 2

Hello and thanks for CodeRunner which I've started using with my students.

It seems that the strdup() function, although available in the library, is NOT defined in string.h.

__tester__.c: In function ‘main’:
__tester__.c:8:16: error: implicit declaration of function ‘strdup’; did you mean ‘strcmp’? [-Werror=implicit-function-declaration]
     char * p = strdup("7\n6\n8\n2\n");

Can it be because it's not a ISO C function but a POSIX One?


In reply to Emmanuel Lazard

Re: strdup not in string.h?

by Richard Lobb -

By default Jobe runs C tasks as C99. See, and strdup is not part of the C99 standard. There are various solutions, such as the following (all untested - caveat emptor):

  1. If it's just for one question, and it's a write-a-function question you can change the template to include the line 
    #define _POSIX_C_SOURCE 200809L
    before the #include of string.h
  2. Tell the students to add that line to their code.
  3. Or tell the students to simply declare the function themselves instead, e.g.
    char* strdup(const char*);
  4. Customise the question and (under advanced customisation) set the sandbox parameters to define a different compileargs value, e.g. {"compileargs": ["-Wall", "-Werror", "-std=gnu++0x", "-x c"]}
  5. Change the base prototype for the C questions to use the above sandbox parameters. [Not recommended, as you'll have to re-do it whenever CodeRunner is upgraded. And you need to be a Moodle admin to see the base prototypes.]
  6. Define your own question types with names like c_program_gnu and c_function_gnu, that use the above compileargs options. Read the documentation carefully before doing this.