Buffer overflows when using sprintf assigning to char array with char pointer as one of the inputs

StackOverflow https://stackoverflow.com/questions/19636364

Question

I use sprintf to create a char array that can later be written out as a call to the system.

char buffer[80];
char *ip = inet_ntoa(sa.sin_addr);
short port = 1;
sprintf(buffer, "Command with IP %s and port %d",ip, port);
system(buffer);

Now in theory this buffer should have plenty of space allocated for this string. But somehow, due to the char pointer, I still get * stack smashing detected * as an error.

Can't sprintf handle the char pointer as input, perhaps because it has a large allocation itself?

EDIT:

It turns out the buffer was to small after all, at least for some arguments.

Was it helpful?

Solution

Since you have C++ tagged, and not C, your code would be better written as:

std::string ip = "0.0.0.0";
int port = 1;
std::ostringstream oss;
oss << "Command with IP:  " << ip << " and port " << port;
system(oss.str().c_str());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top