Home > Software design >  How to fix Segmentation Fault (core dumped) error when using sprintf for system commands in C
How to fix Segmentation Fault (core dumped) error when using sprintf for system commands in C

Time:12-24

I am experimenting with using system commands in C , and I am trying to make a 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:

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

How do I fix this error?

CodePudding user response:

I strongly suggest to not mix C and C when not needed. That means, use the C versions of the C headers and only use the C headers when you need to. In C there is std::string which can be concatenated via .

In your code ip is a single character and cmd is just a pointer. You fail to make it point to some allocated memory. Hence the runtime error when trying to write to the memory pointed to by cmd.

#include <string>
#include <iostream>
#include <cstdlib>
    
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. It lets the user execute arbitrary commands. I strongly suggest to at least check that ip is a valid ip and not something else. See here: How do you validate that a string is a valid IPv4 address in C ?

  • Related