0

The program below is intended to output random noise as a .pbm. The program works perfectly with a height and width < 500. But with a size of 1000 it segfaults yet still generates the image.

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

#define HEIGHT 1000
#define WIDTH 1000

int main(void) {
    FILE *output = fopen("./output.pbm", "wb");
    char *magicNumber = "P1";
    fprintf(output, "%s\n", magicNumber);
    
    char *heightWidthIndicator;
    sprintf(heightWidthIndicator, "%i %i", HEIGHT, WIDTH);

    fprintf(output, "%s\n", heightWidthIndicator);
    for (int j = 0; j < HEIGHT; ++j) {
        char* row = (char*) malloc((sizeof(char) * WIDTH)); 
        for (int i = 0; i < WIDTH; ++i) {
            // Ascii = +48 for integers 
            row[i] = (char) (rand() % 2) + 48;
        }

        fprintf(output, "%s", row);
        free(row);
        fprintf(output, "\n");
    }
    printf("Program done\n");
    fclose(output);
    return 0;
}
83649s
  • 1
  • 2
  • What is you actual question? Is it the seg fault? Or is it why the output is correct even though it seg faults? The former is because you are writing to an uninitialized pointer `char *heightWidthIndicator; sprintf(heightWidthIndicator,..`. The latter is due to Undefined Behaviour from the first error. – kaylum Jun 30 '22 at 01:35
  • The question is that of why the segfault is occouring. I apolgize for making my question to vague. – 83649s Jun 30 '22 at 01:39

0 Answers0