Newshot

AI解决了C语言中所有空指针解引用问题

Translation(model translation, not the source's own text)

文章标题:AI 解决了 C 语言中所有空指针解引用问题

正文: 我是一名 JavaScript 开发者。看看它有多严格、多有表现力:


        $ node
> null = "safe as Rust!"
Uncaught SyntaxError: Invalid left-hand side in assignment
> undefined = "I ❤️ JS"
'I ❤️ JS'
      

给 undefined 赋值就是常识。我最近开始学 C,它简直没法用——我学到的所有最佳实践都不管用,但是,多亏了 AI,我们可以修好它:


        int main(void)
{
    int *ptr = NULL;
    *ptr = 42;
    printf("works %d\n", *ptr);
}
      

运行它会因为空指针解引用而段错误,但对我这个 JavaScript 开发者来说,这完全说不通——NULL 指针本质上就是地址 0x0000000000000000。为什么我不能往那里存东西?它和其他任何地址一样好。Linux 进程运行在虚拟地址空间中——应用不会直接写 RAM 的物理地址。相反,操作系统为每个进程维护一张映射表:[0x4000; x8000] 这段虚拟地址范围可能映射到物理 RAM 中的 [0x187631873600, 0x187631877600]。每个进程都以为自己可以写 RAM 的任意位置,而内核保证进程之间永不冲突。虚拟内存显然就是为了让进程能安全地写 null 而创造的。

我让 AI 来修,它找到了铁证——一个内核配置错误:DEFAULT_MMAP_MIN_ADDR 参数默认是 4096,这意味着前 4096 字节的内存是未映射的。任何对它们的访问都会触发页错误。内核检查是否存在虚拟内存映射,如果什么都没有,就返回 SIGSEGV。

我们只需用 DEFAULT_MMAP_MIN_ADDR=0 重新编译内核,现在就能无错误地对空指针读写,正如上帝所愿:


        $ cc -static -Wl,-N,-Ttext-segment=0,--defsym=__ehdr_start=0 "$HOME/main.c" -o "$HOME/for_real"
$ ./for_real
works 42
      

又一個 AI 解决了人类几十年都解决不了的问题的例子。

References

  • https://www.destroyallsoftware.com/talks/wat WAT
  • https://github.com/torvalds/linux/blob/7b7fe306dd86b5342d3be8a3f1cbf3bb1ebf280f/mm/Kconfig#L738-L755 某个芬兰老哥的玩具内核

The translation is machine-generated and individual terms may be off. Nothing is rewritten or cut; the original is authoritative.

Published by HN AI
This site only summarises and aggregates; copyright stays with the original author. Headlines and summaries follow the source — where they differ, the original wins.
Read the original ↗