简体   繁体   English

在 C++ 中使用 sprintf 执行系统命令时如何修复分段错误(核心转储)错误

[英]How to fix Segmentation Fault (core dumped) error when using sprintf for system commands in C++

I am experimenting with using system commands in C++, and I am trying to make a pinger.我正在尝试在 C++ 中使用系统命令,并且正在尝试制作一个 pinger。 Below is my script:下面是我的脚本:

#include <stdlib.h>
#include <iostream>
#include <stdio.h>
using namespace std;

int main()
{
char ip;
char *cmd;
cout << "Input IP: ";
cin >> ip;
sprintf(cmd, "ping %s", ip);
system(cmd);
return 0;
}

The code compiles and runs fine until you enter the IP you want to ping, at which point it gives me this:代码编译并运行良好,直到您输入要 ping 的 IP,此时它给了我这个:

Input IP: 8.8.8.8
Segmentation fault (core dumped)

I suspect it has something to do with sprintf, but I'm not sure since I'm a beginner when it comes to coding in C++我怀疑它与 sprintf 有关,但我不确定,因为我是 C++ 编码的初学者

How do I fix this error?如何修复此错误?

I strongly suggest to not mix C and C++ when not needed.我强烈建议不要在不需要时混合 C 和 C++。 That means, use the C++ versions of the C headers and only use the C headers when you need to.这意味着,使用 C 接头的 C++ 版本,并且仅在需要时使用 C 接头。 In C++ there is std::string which can be concatenated via + .在 C++ 中有std::string可以通过+连接。

In your code ip is a single character and cmd is just a pointer.在您的代码ip是单个字符, cmd只是一个指针。 You fail to make it point to some allocated memory.你没有让它指向一些分配的 memory。 Hence the runtime error when trying to write to the memory pointed to by cmd .因此,尝试写入 cmd 指向的cmd时会出现运行时错误。

#include <string>
#include <iostream>
#include <cstdlib>
using namespace std;

int main() {
    std::string ip;
    std::cout << "Input IP: ";
    std::cin >> ip;
    std::string cmd = std::string{"ping "} + ip;
    std::system(cmd.c_str());
}

Note that calling system with user input is a security risk.请注意,使用用户输入调用system存在安全风险。 I strongly suggest to at least check that ip is a valid ip and not something else.我强烈建议至少检查ip是有效的 ip 而不是别的。 See here: How do you validate that a string is a valid IPv4 address in C++?请参阅此处: 如何验证字符串是 C++ 中的有效 IPv4 地址?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM