Confused by segfault with legitimate call to strerror(3) on amd64 / sysctl(3) setting `odd' errno's

Christoph Mallon christoph.mallon at
Fri Jan 16 00:53:03 PST 2009

Garrett Cooper schrieb:
> Hi amd64 and Hackers,
>     Uh, I'm really confused why 1) this error (errno => ENOMEM) would
> occur when I have more than enough free memory (both on x86 and amd64)
> and 2) why strerror would segfault in the call to errx in the attached
> sourcefile on amd64 only. Not initializing len causes the second
> output sample (errno => 14, which is EFAULT).
>     Any ideas?
>     Please CC me if mailing on amd64@ as I'm not subscribed to the list.
> Thanks,
> -Garrett

len is not uninitialised. This leads to undefined behaviour. Anything 
can happen. Probably the syscall overwrites parts of the stack because 
len has some (random) high value.

> /* Program */
> #include <err.h>
> #include <errno.h>
> #include <stdio.h>
> #include <sys/types.h>
> #include <sys/sysctl.h>
> int
> main() {
>         int mib[4];
>         size_t len;
>         if (sysctlnametomib("kern.ipc.shmmax", mib, &len) != 0) {
>                 printf("Errno: %d\n", errno);
>                 errx(errno, "Error: %s", strerror(errno));

The use of errno is wrong. printf might change errno. Store the errno 
into a local variable before you do any call, which might modify it.

More information about the freebsd-hackers mailing list