0

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);
}

2 Answers2

1
  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);
    
Kninnug
  • 7,992
  • 1
  • 30
  • 42
  • Oh! So the check=...and the print_pixel both go into the while loop? (Since I only executed check=... once) Sorry, I haven't seen that: do{ notation before, does that mean do it in the while loop? Or before? Thanks! –  Jun 02 '13 at 01:08
  • Also, I'm wondering if there's a problem with my print_pixel function. Because, I want to print it to the output file, so would I have to use fprintf instead of printf? (I've tried doing this, but that would mean that I would need "output" as the first argument of fprintf, and I don't declare "output" until after the print_pixel function) –  Jun 02 '13 at 01:13
  • You can pass `output` as an argument to `print_pixel`: `void print_pixel(FILE * output, int a){ ...` – Kninnug Jun 02 '13 at 12:30
  • Thanks for all the tips/help guys! :) –  Jun 02 '13 at 21:33
0

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");
 [...]
Till
  • 27,559
  • 13
  • 88
  • 122