c - 与编译器优化结合的段错误

标签 c segmentation-fault return

我的代码使用 union 来表示 RGB 像素。它在 Debug模式下运行良好,但启用编译器优化后,它会出现段错误。

您可以在下面看到用于重现错误的简化测试代码。我的系统是带有 GCC4.8.2 的 Ubuntu。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>

union Pixel {
    uint32_t color;
    uint8_t at[4];
};

typedef struct Screen {
    union Pixel *pixels;
    int width;
    int height;
    int rPosition;
    int gPosition;
    int bPosition;
} *Screen;

Screen ScreenCreate(int width, int height, uint32_t rPosition, uint32_t gPosition, uint32_t bPosition) {
    Screen this = malloc(sizeof *this);
    this->pixels = malloc(width * height * sizeof this->pixels[0]);
    this->width = width;
    this->height = height;
    this->rPosition = rPosition;
    this->gPosition = gPosition;
    this->bPosition = bPosition;
}

void ScreenDelete(Screen this) {
    free(this->pixels);
    free(this);
}

void ScreenFill(Screen this, uint8_t r, uint8_t g, uint8_t b) {
    union Pixel pixel;
    pixel.color = 0;
    pixel.at[this->rPosition] = r;
    pixel.at[this->gPosition] = g;
    pixel.at[this->bPosition] = b;
    for (int i = 0; i < this->width * this->height; i += 1) {
        this->pixels[i].color = pixel.color;
    }
}

int main(void) {
    Screen screen = ScreenCreate(500, 500, 2, 1, 0);
    ScreenFill(screen, 0xff, 0xff, 0xff);
    ScreenDelete(screen);
    return 0;
}

最佳答案

在您的 ScreenCreate() 函数中,您忘记了 return 语句。因此,您的代码会产生未定义的行为。

最后一行应该是

 return this;

相关:根据 C11 标准,第 6.9.1 章,函数定义,第 12 段

If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.

因此,在 main() 中使用 screen 导致 undefined behaviour .

故事的寓意:启用编译器警告并留意它们。

关于c - 与编译器优化结合的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29696455/

相关文章:

c - 使用具有多个条件的 while 循环

c - 自动发现 C 依赖项

c - C上的指针,需要简单验证

c - 需要帮助我在 C 程序中遇到段错误

c - 无法理解这个函数的返回值

ruby - Ruby 方法应该返回 nil 还是空对象

c++ - 在返回 shared_ptr 的函数中返回新的东西

c++ - "This version of C:\TURBOC3\BIN\TCC.EXE is not compatible with the version of Windows you' 重新运行。

c - 使用三维动态矩阵时的分割错误

C++ 复制构造函数/赋值运算符错误