kbreezy
kbreezy

Reputation: 19

Getting a random segmentation error

I'm getting a weird segmentation fault: 11 error when i run this C file with gcc -std=gnu90 . From what I read, somewhere in my code it is exceeding memory? But, After doing a lot of debugging, I am not sure where is it exceeding. I'm giving my height and width as 160 and 240 respectively for a small bmp file.

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

void brighten(int,int,char*);
//void contrast(int height, int width, char* file);
//void rotation(int height, int width, char* file);

#define HEADER_SIZE 54

int main(void) {
    printf("Enter the filename: ");
    char file[256];
    scanf("%s", file);
    printf("Enter the height and width (in pixels): ");
    int height, width;
    scanf("%d %d",&height,&width);
    strcat(file,".bmp");
    brighten(height,width,file);
    //contrast(height,width,file);
    //rotation(height,width,file);
    return 0;
}

void brighten(int height, int width, char* file) {
    FILE *input = fopen(file,"rb");
    FILE *output = fopen("copy1.bmp","wb");
    char header[HEADER_SIZE];
    unsigned char pixels[height][width * 3];
    fread(header,1,HEADER_SIZE,input);
    fread(pixels,1,height * width * 3,input);

    int r, c;

    for( r = 0; r < height; r++) {
        for(c = 0; c < width * 3; c++) {
            pixels[r][c] += 50;
            if( pixels[r][c] > 255) {
                pixels[r][c] = 255;
            }
            printf(" %c \n",pixels[r][c]);
        }
    }
    fwrite(header,sizeof(char), HEADER_SIZE,output);
    fwrite(pixels,sizeof(char),height * width * 3, output);
    fclose(input);
    fclose(output);
}

Upvotes: 0

Views: 173

Answers (1)

Amit Singh
Amit Singh

Reputation: 3063

As commented by @Chris, you should check if fopen() returns NULL. Performing read/write operations on a NULL pointer leads to segmentation fault.

As per GNU C Library manual :

If the open fails, fopen() returns a null pointer.

fopen() may give NULL value due to various reasons ( but not limited to ) :

  • Non-existence of the file
  • Not having required permissions for the file

It is recommended to check errno in case fopen() returns NULL.

Upvotes: 1

Related Questions