Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segfault in C from printf, no warning

Tags:

c

Here is a short simple program which segfaults when run. It gives no warnings on clang, even at pedantic level.

#include <stdio.h>
#include <stdlib.h>

typedef struct object {
    int type;
} object;

void write(object *obj) {
    switch (obj->type) {
    case 1:
        break;
    }
}

int main(void) {
    printf("hi");
    return 0;
}

The crash doesn't seem to happen on x86 Linux, but I'm on aarch64 Android.

$ gcc --version
clang version 17.0.6
Target: aarch64-unknown-linux-android24
Thread model: posix
InstalledDir: /data/data/com.termux/files/usr/bin

$ uname -a
Linux localhost 5.10.177-android13-4-00003-ga7208022a7ea-ab10815828 #1 SMP PREEMPT Fri Sep 15 16:40:54 UTC 2023 aarch64 Android

Tracing it with gdb makes it seem like printf ends up calling write, but I've no idea now that could come about.

This looks like a compiler bug, but I can compile and run other programs fine. If I remove the printf from main or the definition of write then this runs as expected. Can someone explain what's going on?

like image 914
Tumok A. Byrd Avatar asked Nov 01 '25 19:11

Tumok A. Byrd


1 Answers

write is the name of a library function. Creating a function with this name can override the library function and result in it getting called instead. The implementation of printf most likely uses write.

Definition functions or variables with the same name as reserved library functions can trigger undefined behavior in your code, so change the name to something else.

like image 140
dbush Avatar answered Nov 04 '25 13:11

dbush



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!