使用 sprintf 分配给字符数组并将字符指针作为输入之一时缓冲区溢出

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

本文关键字:字符 缓冲区 一时 输入 溢出 分配 sprintf 数组 使用 指针      更新时间:2023-10-16

我使用 sprintf 创建一个 char 数组,稍后可以将其写出作为对系统的调用。

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);

现在理论上,这个缓冲区应该有足够的空间分配给这个字符串。但不知何故,由于字符指针,我仍然* stack smashing detected *为错误。

sprintf 不能将字符指针作为输入处理,也许是因为它本身的分配很大?

编辑:

事实证明,缓冲区毕竟很小,至少对于某些参数而言。

由于您标记了C++而不是 C,因此您的代码最好编写为:

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());