Jordan
Jordan

Reputation: 1614

bmp segmentation fault in C

I'm making bmp images of fractals (Mandelbrot's and BuddaBrot's) in a square frame and if I make the width 1000 pixels, no problem, but if I increase its width to 2000 I get a segmentation fault on the fist line of the program. Whats happening. Here is my code:

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include <time.h>

...

#define HEIGHT 2000
#define WIDTH  2000




typedef struct _pixel{
unsigned char blue;
    unsigned char green;
unsigned char red;
}pixel;



typedef pixel screen[WIDTH][HEIGHT];

typedef struct _frame{
    pair width;
    pair height;
}frame;

void printPixel(screen view);


void editPixel(screen view, int row, int col, pixel p);
void blankScreen(screen view);


int main(int argc, const char * argv[])
{ 



    FILE *out; 
    out = fopen("Out.bmp", "w");


    int localHeight = HEIGHT - HEIGHT%4;
    int localWidth = WIDTH - WIDTH%4;
    frame myFrame = getFrame(localWidth,localHeight);

    assert((myFrame.height.small+myFrame.height.big*256)==HEIGHT - HEIGHT%4);
    assert((myFrame.width.small+myFrame.width.big*256)== WIDTH - WIDTH%4);

    unsigned char bmp[] = {
        0x42,0x4D,0x5A,0x00,0x00,0x00,0x00,0x00,
        0x00,0x00,0x3C,0x00,0x00,0x00,0x28,0x00,
        0x00,0x00,myFrame.width.small,myFrame.width.big,0x00,0x00,
        myFrame.height.small,myFrame.height.big,  
        0x00,0x00,0x01,0x00,0x18,0x00,0x00,0x00,
        0x00,0x00,0x24,0x00,0x00,0x00,0x13,0x0B,
        0x00,0x00,0x13,0x0B,0x00,0x00,0x00,0x00,
        0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x99,
        0x00,0x00,0x00,0x00,};
        //Write the header
    fwrite(bmp, 1, sizeof(bmp), out);

    screen view;
    blankScreen(view); //clears the image to a blank

    printPixel(view); // this gets the image


    fwrite(view, 1, sizeof(screen), out); //writes the image
    fclose(out); //closes the file

    return EXIT_SUCCESS;
}

Upvotes: 0

Views: 302

Answers (1)

MByD
MByD

Reputation: 137352

You are getting a stack overflow, as you fail to allocate 2000 * 2000 pixels on the stack (the line screen view;), as the stack is just too small for that. Allcoate the memory dynamically (using malloc).

pixel * view;
view = malloc(sizeof(pixel) * HEIGHT * WIDTH);
if (view == NULL) return 1; //failed to allocate

// change those two functions to handle a "pixel *" instead of pixel[HEIGHT][WIDTH]
blankScreen(view);
printPixel(view); 

Upvotes: 2

Related Questions