1

According to the man page strerror(errnum) returns a char *, but I get the following warning:

gcc temp.c -o temp
temp.c: In function ‘mystrerror’:
temp.c:10:4: warning: return makes pointer from integer without a cast [enabled by default]

I get a segfault When I run it with ./temp 0 but not ./temp 256.

Could someone explain why this happens and how to fix it (if possible)?

temp.c

#include <stdio.h>
#include <errno.h>

char *mystrerror(int errnum)
{
    switch (errnum) {
    case 256:
        return "My test";
    default:
        return strerror(errnum);
    }
}

int main(int argc, char **argv)
{
    int err;

    if (argc > 1) {
        err = atoi(argv[1]);
        printf("test error (%d) %s\n", err, mystrerror(err));
    }

    return 0;
}
E-rich
  • 9,243
  • 11
  • 48
  • 79

2 Answers2

4

According to the strerror manpage its include is #include <string.h>.

Without a function definition C assumes every function returns int, which is why you are getting that compiler error.

Zan Lynx
  • 53,022
  • 10
  • 79
  • 131
4

You are missing the inclusion of the <string.h> header file.

Documentation.

The compiler even tells you what exactly your problem is:

return makes pointer from integer without a cast

If there's no prototype present for a function, then it's assumed to return int. And it appears that on your platform, a pointer to char does not fit into an int, hence its truncated, and then printf() tries to dereference the thus invalid pointer.

  • Well, if you're interested what **exactly** the problem is, use `-Wall` – Karoly Horvath Jun 18 '13 at 16:31
  • 1
    @KarolyHorvath One **does always** use `-Wall`. (And I use `-Wextra -pedantic -pedantic-errors` as well, but maybe I'm just masochistic.) –  Jun 18 '13 at 16:32
  • 1
    Actually C99 dropped the default `int` rule; calling a function with no visible declaration is just illegal (actually a constraint violation). But many compilers, including gcc, operate under the old rules by default. – Keith Thompson Jun 18 '13 at 17:28
  • @KeithThompson Yes, that's correct, both `gcc` and `clang` refuse to issue a diagnostic unless `-std=c99 -pedantic` is present, actually. –  Jun 18 '13 at 17:30
  • 1
    Software would have a lot fewer bugs if they made this a fatal error except when `-std=c89` is specified. – R.. GitHub STOP HELPING ICE Jun 18 '13 at 17:47