首页 > 解决方案 > 当我在 Docker 中运行使用 G ++ 编译的程序时的不同行为

问题描述

如果可执行文件在 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

Dockerfile:

FROM debian
RUN apt-get update && apt-get install -y \
   libssl-dev
COPY fast/ /usr/local/
ENTRYPOINT ["usr/local/FastCompile"]

$docker build -t 快速编译。

$docker 运行快速编译

BEFORE SPRINTF 003395


AFTER SPRINTF P

如果我删除 -Os 并重新编译:

g++ -o FastCompile FastCompile.c -DNDEBUG 

Docker 内部的行为是正确的。

那么,这是一个 Docker 问题吗?还是预期的行为?

标签: c++dockerg++compiler-optimization

解决方案


您的代码具有未定义的行为。

sprintf(cAux2, "%s%c", cAux2, (nRest+65));

读取和写入同一个对象。要修复它,您可以cOrd在调用中使用,这样您就不会从缓冲区中读取。那看起来像

sprintf(cAux2, "%s%c", cOrd, (nRest+65));

另请注意,它(nRest+65)为您提供了 a int,而不是char格式说明符声明的 a 。这也是未定义的行为。您需要将其转换为 char 来修复它

sprintf(cAux2, "%s%c", cOrd, char(nRest+65));

推荐阅读