枚举数据类型和 gcc
我有一个函数,其中函数参数之一是整数。 在函数调用期间,我将枚举数据类型传递给该函数。 使用 gcc 构建后,对函数内的 INTEGER 变量的任何访问都会导致分段错误。
示例代码:
void somefun (unsigned int nState)
{
switch (nState) // <-- Crashes on this line
{
//
// functionality here ...
//
}
}
enum {
UNDEFINED = -1,
STATE_NICE,
STATE_GREEDY
} E_STATE;
int main (int argc, char *argv [])
{
somefun (STATE_NICE);
}
I have a function in which one of the function arguments is an integer. During function invocation I am passing an enumerated datatype to this function. After building using gcc, any access to the INTEGER variable inside the function causes a segmentation fault.
Sample code:
void somefun (unsigned int nState)
{
switch (nState) // <-- Crashes on this line
{
//
// functionality here ...
//
}
}
enum {
UNDEFINED = -1,
STATE_NICE,
STATE_GREEDY
} E_STATE;
int main (int argc, char *argv [])
{
somefun (STATE_NICE);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
首先,枚举是在 main() 中定义的,并且在 somefun() 中不存在。 您应该在 main 之外定义枚举,尽管我看不出这是如何导致崩溃的。
在 main 之外定义枚举后,您应该将 somefun 定义为 somefun( E_STATE nState ) 并再次测试。
First off, The enum is defined in main() and does not exist for somefun(). You should define the enum outside of main, although I cannot see how this is causing a crash.
After defining the enum outside of the main you should define somefun to be somefun( E_STATE nState ) and test again.
我使用 gcc 版本 4.2.4 在我的计算机上准确地编译并运行了该代码(剪切和粘贴),没有错误或分段错误。 我相信问题可能出在其他地方。
I compiled and ran that code exactly (cut & paste) on my computer, using gcc version 4.2.4, with no errors or segmentation fault. I believe the problem might be somewhere else.
实际上为我运行:
做了一些更改,但没有它们就运行了。 (1) 在开关中添加一个标签,这样它就有了一些东西; (2) 添加了
#include
和printf
这样我就可以知道它已经运行了; (3) 添加了return 0;
以消除无趣的警告。它确实成功运行,没有任何更改,只是没有做任何可见的事情。
那么,什么是操作系统,什么是硬件架构?
更新
在我尝试时代码发生了变化,所以这里是对更新版本的测试:
仍然有效。 您的版本中是否有核心文件? 您是否尝试过获取堆栈跟踪?
Actually runs for me:
Made a couple of changes, but it ran without them. (1) added a tag in the switch just so it had something; (2) added the
#include <stdio.h>
andprintf
so I could tell that it had run; (3) added thereturn 0;
to eliminate an uninteresting warning.It did run successfully with none of the changes, it just didn't do anything visible.
So, what's the OS, what's the hardware architecture?
Update
The code changed while I was trying it, so here's a test of the updated version:
Still works. Are you getting a core file in your version? Have you tried getting a stack trace?
您的情况类似于 sun sparc 硬件或类似硬件。 请发布 uname -a 和 dmesg 的输出
Your situation is like specific to sun sparc hardware or similar. Please post uname -a and output of dmesg
从您的所有回答来看,代码在逻辑上似乎是正确的,我需要调查崩溃的真正原因。 我会调查并尽快发布。
From all your answers it seems that the code is logically correct, and I need to investigate the real reason for the crash. I will investigate it and post it soon.