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)?
#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.
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.