当我 运行 在 Docker 中用 G ++ 编译的程序时的不同行为
Different behavior when I running a program compiled with G ++ in Docker
如果可执行文件在 docker 内或在主机上 运行,则其行为会有所不同。但这只有在我们更改 G++ 的优化级别时才会发生。
编译器:
g++ (Ubuntu 7.3.0-27ubuntu1~18.04) 7.3.0
我正在尝试执行以下代码:
#include <cstdio>
#include <cstring>
int main()
{
int nOrd =3395;
char cOrd[] = "003395";
char cAux2[256];
strcpy(cAux2, cOrd);
int nRest = nOrd % 26;
printf("BEFORE SPRINTF %s\n\n\n", cAux2);
sprintf(cAux2, "%s%c", cAux2, (nRest+65));
printf("AFTER SPRINTF %s\n\n\n", cAux2);
return 0;
}
如果我编译:
g++ -o FastCompile FastCompile.c -DNDEBUG -Os
而我运行在主机中。输出符合预期:
BEFORE SPRINTF 003395
AFTER SPRINTF 003395P
如果我用这个可执行文件和 docker 中的 运行 创建一个图像,我有:
Docker 版本 18.09.4,构建 d14af54266
Docker文件:
FROM debian
RUN apt-get update && apt-get install -y \
libssl-dev
COPY fast/ /usr/local/
ENTRYPOINT ["usr/local/FastCompile"]
$docker build -t fastcompile .
$docker 运行 快速编译
BEFORE SPRINTF 003395
AFTER SPRINTF P
如果我删除 -Os 并重新编译:
g++ -o FastCompile FastCompile.c -DNDEBUG
Docker 中的行为是正确的。
所以,
是 Docker 问题吗?或者这是预期的行为?
您的代码有未定义的行为。
sprintf(cAux2, "%s%c", cAux2, (nRest+65));
读取和写入同一个对象。要修复它,您可以在调用中使用 cOrd
这样您就不会从缓冲区中读取数据。那看起来像
sprintf(cAux2, "%s%c", cOrd, (nRest+65));
另请注意,(nRest+65)
给您的是 int
,而不是格式说明符规定的 char
。这也是未定义的行为。你需要把它转换成一个字符来修复它,比如
sprintf(cAux2, "%s%c", cOrd, char(nRest+65));
如果可执行文件在 docker 内或在主机上 运行,则其行为会有所不同。但这只有在我们更改 G++ 的优化级别时才会发生。
编译器: g++ (Ubuntu 7.3.0-27ubuntu1~18.04) 7.3.0
我正在尝试执行以下代码:
#include <cstdio>
#include <cstring>
int main()
{
int nOrd =3395;
char cOrd[] = "003395";
char cAux2[256];
strcpy(cAux2, cOrd);
int nRest = nOrd % 26;
printf("BEFORE SPRINTF %s\n\n\n", cAux2);
sprintf(cAux2, "%s%c", cAux2, (nRest+65));
printf("AFTER SPRINTF %s\n\n\n", cAux2);
return 0;
}
如果我编译:
g++ -o FastCompile FastCompile.c -DNDEBUG -Os
而我运行在主机中。输出符合预期:
BEFORE SPRINTF 003395
AFTER SPRINTF 003395P
如果我用这个可执行文件和 docker 中的 运行 创建一个图像,我有:
Docker 版本 18.09.4,构建 d14af54266
Docker文件:
FROM debian
RUN apt-get update && apt-get install -y \
libssl-dev
COPY fast/ /usr/local/
ENTRYPOINT ["usr/local/FastCompile"]
$docker build -t fastcompile .
$docker 运行 快速编译
BEFORE SPRINTF 003395
AFTER SPRINTF P
如果我删除 -Os 并重新编译:
g++ -o FastCompile FastCompile.c -DNDEBUG
Docker 中的行为是正确的。
所以, 是 Docker 问题吗?或者这是预期的行为?
您的代码有未定义的行为。
sprintf(cAux2, "%s%c", cAux2, (nRest+65));
读取和写入同一个对象。要修复它,您可以在调用中使用 cOrd
这样您就不会从缓冲区中读取数据。那看起来像
sprintf(cAux2, "%s%c", cOrd, (nRest+65));
另请注意,(nRest+65)
给您的是 int
,而不是格式说明符规定的 char
。这也是未定义的行为。你需要把它转换成一个字符来修复它,比如
sprintf(cAux2, "%s%c", cOrd, char(nRest+65));