Question

I'm given an image file and the real image is hidden behind random pixels. I have to decode the image by multiplying the red value by 10 and by setting the green/blue values equal to that new red value. (And I can't go past the max value for color which is 255) When I run this program, it should create an output file called "hidden.ppm". I ran my program, but all I got was "Segmentation Fault" and I can't figure out why.

void print_pixel(int a)
{
   int r, g, b;

   r = a * 10;
   g = r;
   b = r;

   if (r > 255)
   {
      r = 255;
   }

   if (g > 255)
   {
      g = 255;
   }

   if (b > 255);
   {
      b = 255;
   }

   printf("%d\n", r);
   printf("%d\n", g);
   printf("%d\n", b);
}

void decode(int arg_list, char *in[])
{
   FILE *input, *output;
   int check, value;

   fprintf(output, "P3\n");
   fprintf(output, "%d %d\n", 1024, 768);
   fprintf(output, "255\n");

   input = fopen(in[1], "r");
   output = fopen("hidden.ppm", "w");

   check = fscanf(input, "%d\n", &value);

   while (check != EOF)
   {
      print_pixel(value);
   }
}

int main(int argc, char *argv[])
{
   if (argc == 0)
   {
      printf("usage: a.out <input file>\n");
      return 1;
   }

   decode(argc, argv);
}
Was it helpful?

Solution

  1. You're using output before fopening it.

  2. Your while loop is infinte, because you only execute check = fscanf(input, "%d\n", &value); once. You probably meant:

    do{
        check = fscanf(input, "%d\n", &value);
        print_pixel(value);
    while(check != EOF);
    

OTHER TIPS

In your decode implementation, you are accessing the output stream before initializing it. Move the opening of the output file above the fprintf's .

void decode(int arg_list, char *in[])
{
   FILE *input, *output;
   int check, value;

   input = fopen(in[1], "r");
   output = fopen("hidden.ppm", "w");

   fprintf(output, "P3\n");
 [...]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top