程序在 make 启动时运行,但不是通过 shell 启动,为什么?
我编写了一个 C 程序,其中进行了一些相当大的堆栈分配,大约 2 MiB。 由于我使用穷人的 IDE*,每次编译时,我都会通过 make 自动运行该程序以对其进行测试。
我几乎已经完成了所有内容,但由于某种原因,在一些最终优化过程中,我直接从 shell 运行它。 瞬间出现段错误! 使用 make 运行它仍然有效,并且手动运行它总是会产生相同的段错误。
我最终将所做的堆栈分配量减少到 256 KiB,这解决了问题。 我的理由是 make 可能正在执行该进程,因此它继承了一些奇怪的参数,使其可以使用更多的堆栈空间。
虽然现在一切都很好,但我无法检验我的理论。 任何人都可以确认或否认,或建议某种测试方法吗?
* zsh、vim、gcc、gdb 和一些坚果 makefile
I wrote a C program in which I did some pretty heavy stack allocation, around 2 MiB. Since I use the poor man's IDE* I was automatically running the program via make in order to test it, each time I compiled.
I had pretty much wrapped everything up, but for some reason, during some of the final optimization, I ran it directly from the shell. Instant segfault! Running it with make still worked, and running it by hand always produced the same segfault.
I eventually reduced the amount of stack allocation I was doing to 256 KiB, which solved the problem. My rationale was that make was probably exec-ing the process, and thus it was inheriting some weird parameters that allowed it to use more stack space.
Although everything is fine now, I have no way of testing my theory. Can anyone confirm or deny, or suggest some way of testing?
* zsh, vim, gcc, gdb, and some nutty makefiles
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以尝试使用 ulimit(1) 设置最大堆栈大小,看看是否有效:
You can try setting the maximum stack size with ulimit(1) and see if it works:
就我个人而言,我的第一步是尝试通过 gdb 或调试 printf 或其他方式找到代码中发生段错误的位置。 (这就是为什么你总是检查 malloc 的返回值,它减少了段错误的可能来源;-p)一方面,找到问题的确切来源可以为你提供支持或反对你的堆栈分配理论的证据; 此外,它还可以让您插入错误检查代码,以便程序可以正常退出并显示信息丰富的错误消息,而不是出现段错误。
Personally, my first step would be to try to locate where in the code the segfault occurred, either with gdb or debugging
printf
s or whatever. (This is why you always check return values from malloc, it cuts down on the possible sources of segfaults ;-p) For one thing, finding the exact source of the problem could give you evidence for or against your theory about stack allocation; also, it'll let you insert error-checking code so the program can exit gracefully with an informative error message rather than segfaulting.需要更多信息来诊断这一点。 也就是说,很高兴看到您正在使用的 makefile 和 shell 脚本。
More information is needed to diagnose this. Namely, it'd be nice to see the makefile and the shell scripts which you were using.