سؤال

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;
}
هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top