0

我有一个函数可以读取表面的像素并将最亮的像素的索引写入另一个数组。使用 gdb,我注意到像素数组中的所有值恰好在 3/4 处变为 0,并且在距该点正好 1020 个像素之后,程序段错误。这是代码:

void scanBrightPixels(int** write_to, int* pcount, SDL_Surface* image) {
   SDL_PixelFormat* f = image->format;
   SDL_LockSurface(image);
   Uint32* pixels = (Uint32*) image->pixels;
   SDL_UnlockSurface(image);
   int lpcount = 0;
    for (int i = 0; i < image->w * image->h / 4 * 3; i++) {
        Uint8 r, g, b;
        Uint8 brightness;
        SDL_GetRGB(pixels[i], f, &r, &g, &b); // this is where the segfault happens
        brightness = (Uint8) ((r * 0.33) + (g * 0.5) + (b * 0.16));
        if (brightness >= 251) {
            (*write_to)[lpcount] = i;
            lpcount++;
        }
    }
    *pcount = lpcount;
}

该函数也从 std::async 调用,如果这有所不同的话。有任何想法吗?

4

1 回答 1

0

在使用完像素指针之前,您不应调用 SDL_UnlockSurface。调用解锁后像素可能无效。如果表面存储在 gpu 上,情况尤其如此。否则即使在调用解锁后它也可能意外工作。

此外,也不能保证下一行像素会立即开始,就像您的代码似乎假设的那样,前一行在内存中结束。SDL_Surface 成员间距是内存中 2 个相邻行的开头之间的字节数。

最后,我不确定“/ 4 * 3”在计算循环结束索引时的目的是什么。

我希望这有帮助。

于 2017-05-13T03:10:43.280 回答