I am trying to convert an image to grayscale using SDL and c. When compiling in compiler it doesn’t give me any errors. However, if I try to build the code in the terminal, I get - segmentation fault (core dumped)? I am quite new to C and haven’t managed to find a mistake in my code. Any suggestions would be greatly appreciated.
[code]int main(int argc, char* argv[])
//Declaring pointers
SDL_Window *window;
SDL_Renderer *renderer;
SDL_Event event;
SDL_Texture *texture;
int i, quit;
Uint32 *pixels;
/* Check command line usage */
if ( ! argv[1] ) {
fprintf(stderr, "Give an image file: %s
", argv[0]);
}
//Initializing window and renderer
SDL_Init(SDL_INIT_VIDEO);
//Creating a window
if (SDL_CreateWindowAndRenderer(640, 480, SDL_WINDOW_RESIZABLE, &window, &renderer))
{
printf("Couldn’t open the window: %s
", SDL_GetError());
}
//Option to display in fullscreen
//Taken from Compting fro Graphics lesson, imagine.c file
for ( i=1; argv[i]; i++) {
if ( strcmp(argv[i], “-fullscreen”) == 0 ) {
continue;
}
}
//Code from imagine.c ends
//Load an image
SDL_Surface * image = IMG_Load(argv[i]);
if (!image)
{
fprintf(stderr, "Couldn’t load the image %s: %s
", argv[i], SDL_GetError());
}
//Create texture from image
texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STATIC, image->w, image->h);
if (!texture)
{
printf("Couldn’t create texture from image: %s
", SDL_GetError());
}
//Convert surface to ARGB8888 format
image = SDL_ConvertSurfaceFormat(image, SDL_PIXELFORMAT_ARGB8888, 0);
//Surface pixels from void to *Uint32
pixels = (Uint32 *)image->pixels;
quit = 0;
while (!quit) {
SDL_UpdateTexture(texture, NULL, image->pixels, image->w *sizeof(Uint32));
SDL_WaitEvent(&event); {
switch (event.type) {
case SDL_KEYDOWN:
switch (event.key.keysym.sym) {
//Going through y axis
for (int y = 0; y < image->h; y++)
{
//Going through x axis
for (int x = 0; x < image->w; x++)
{
//Converting to grayscale
Uint32 pixel = pixels[y * image->w + x];
Uint8 r = pixel >> 16 & 0xFF;
Uint8 g = pixel >> 8 & 0xFF;
Uint8 b = pixel & 0xFF;
Uint8 v = 0.212671f * r + 0.715160f * g + 0.072169f * b;
pixel = (0xFF << 24) | (v << 16) | (v << 8) | v;
pixels[y * image->w +x] = pixel;
}
case SDLK_LEFT:
if ( i > 1 ) {
i -= 2;
quit = 1;
}
break;
case SDLK_RIGHT:
if ( argv[i+1] ) {
quit = 1;
}
break;
case SDLK_ESCAPE:
case SDLK_q:
argv[i+1] = NULL;
/* Drop through to done */
case SDLK_SPACE:
case SDLK_TAB:
quit = 1;
break;
default:
break;
}
break;
case SDL_MOUSEBUTTONDOWN:
quit = 1;
break;
case SDL_QUIT:
argv[i+1] = NULL;
quit = 1;
break;
break;
}
}
//Show the image
SDL_RenderCopy(renderer, texture, NULL, NULL);
SDL_RenderPresent(renderer);
}
SDL_DestroyTexture(texture);
SDL_FreeSurface(image);
}
//Quit SDL
SDL_Quit();
return (0);[/code]