C (gnu11):嵌套函数段错误



我将C11与GNU扩展(--std=gnu11(一起使用。给定以下带有嵌套函数的代码:

#include <stdio.h>
typedef int (int_f)();
void print_f_res(int_f f) {
printf("f() = %dn", f());
}
void rr(int n) {
int id() {
return n;
}
if (n > 0) {
rr(n - 1);
}
print_f_res(&id);
}

int main() {
rr(3);
return 0;
}

如果我运行它,我得到一个段错误:

➜  /tmp/test gcc -Wall -Wextra -Werror test.c --std=gnu11 -O0 -g
➜  /tmp/test ./a.out
[1]    11713 segmentation fault (core dumped)  ./a.out

如果我用 valgrind 运行它,它可以工作:

➜  /tmp/test valgrind ./a.out
==11491== Memcheck, a memory error detector
==11491== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==11491== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==11491== Command: ./a.out
==11491==
==11491== error calling PR_SET_PTRACER, vgdb might block
f() = 0
f() = 1
f() = 2
f() = 3
==11491==
==11491== HEAP SUMMARY:
==11491==     in use at exit: 0 bytes in 0 blocks
==11491==   total heap usage: 1 allocs, 1 frees, 512 bytes allocated
==11491==
==11491== All heap blocks were freed -- no leaks are possible
==11491==
==11491== For counts of detected and suppressed errors, rerun with: -v
==11491== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
➜  /tmp/test

海湾合作委员会版本:

➜  /tmp/test gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/7/lto-wrapper
OFFLOAD_TARGET_NAMES=nvptx-none
OFFLOAD_TARGET_DEFAULT=1
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu 7.5.0-3ubuntu1~18.04' --with-bugurl=file:///usr/share/doc/gcc-7/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++ --prefix=/usr --with-gcc-major-version-only --program-suffix=-7 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-bootstrap --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-libmpx --enable-plugin --enable-default-pie --with-system-zlib --with-target-system-zlib --enable-objc-gc=auto --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 7.5.0 (Ubuntu 7.5.0-3ubuntu1~18.04)

有谁知道为什么会这样?我是否错误地使用了嵌套函数?

谢谢

找到的解决方案:

我正在使用 WSL,而 WSL 不支持此功能:请参阅 https://nullprogram.com/blog/2019/11/15/和 https://github.com/microsoft/WSL/issues/286

相关内容

  • 没有找到相关文章

最新更新