0

此代码是 C/C++,运行时不会出现警告或调试消息。我在 GNU GCC 编译器中使用 Code::blocks。这个应用程序曾经完美地运行过,然后在我没有注意到的情况下搞砸了。现在每次它都会允许输入一个ip地址,但随后会冻结并关闭。为什么?

#include <iostream>
#include <string>
#include <cstdio>

using namespace std;

int ip[3];
char * inputIP;
int x;
string classValue;

void subnetClass()
{
if (x==0) classValue="Error: first octet may not be zero.";
if (x>0 && x<=126) classValue="Class A";
if (x==127) classValue="Loopback Address";
if (x>=128 && x<=191) classValue="Class B";
if (x>=192 && x<=223) classValue="Class C";
if (x>=224 && x<=239) classValue="Class D";
if (x>=240 && x<=255) classValue="Class E";
if (x>255) classValue="Error: an octet may not be more than 255.";

cout << classValue << endl;
}


int main()
{
cout << "Enter IP address in dotted-decimal form." << endl;
cin >> inputIP;
scanf(inputIP, "%d.%d.%d.%d" , &ip[0],&ip[1],&ip[2],&ip[3]);
int x=ip[0];
subnetClass();

return 0;
}

构建日志:

检查是否存在:C:...\IP subnetting app\bin\Debug\IP subnetting app.exe

执行:“C:...\CodeBlocks/cb_console_runner.exe”“C:...\IP subnetting app\bin\Debug\IP subnetting app.exe”(在 C:...\IP subnetting app.)

进程以 -1073741510 状态终止(0 分 27 秒)

4

3 回答 3

2

您正在声明一个隐藏全局变量的变量“x”。

int x=ip[0];

但是,不要这样做。将一个 int 参数添加到 subnetClass 并以这种方式传递值,然后删除全局变量。

确实,删除所有全局变量应该是一个目标并且很容易实现。有几个只在 main() 中使用。

于 2012-02-01T20:25:42.577 回答
1

It might have worked with a little help from sheer luck even if you messed things up later, I believe. More or less everything is wrong. First you read the line into the area pointed to by uninitialized pointer (or maybe you read the pointer value, I'm not even sure what >> (char*) is supposed to do). You better change the definition to

std::string inputIP;

then you try to parse it used scanf and pass this pointer as a format string. What you meant is using sscanf. Assuming you changed the inputIP type, you can use

sscanf(inputIP.c_str(),"%d....

Then you assign to local main variable x that shadows global, which remains uninitialized when you use it in the function. Just remove the int part in the assignment like this:

x=ip[0];

and make the ip array of four elements.

int ip[4];

Then it may work. Unless I missed something else.

And one more thing: if you use some source control (for instance using git you may start new project in no time) then you'd know what you've changed when you mess up, just commit early, commit often.

于 2012-02-01T20:31:23.147 回答
0

使用sscanf代替scanf

于 2012-02-01T20:25:50.603 回答