0

I'm not sure why I running this (with argv[1] being a ppm image) is causing a segfault. Any thoughts?

unsigned char *image;
char *name;
int sz;

name = argv[1];
FILE *fpt;

fpt = fopen(name,"rb");

fseek(fpt, 0, SEEK_END);
sz = ftell(fpt);
fseek(fpt, 0, SEEK_SET);

image = (unsigned char *) calloc(sz, 1);
fread(image, 1, sz, fpt);
swinters
  • 337
  • 3
  • 5
  • 16
  • On which line does it segfault? Did you verify that fopen() succeeded and did not return NULL? Did you verify that calloc() did not return NULL? – Martin R Feb 12 '14 at 18:54
  • 1
    `sz` should be declared as type `size_t` (see `man calloc` and `man fread`). As a debug check, you could print `sz` to make sure it is what you think it should be in value. – lurker Feb 12 '14 at 18:55
  • 1
    [Please don't cast the return value of `malloc()` and friends, in C](http://stackoverflow.com/a/605858/28169). – unwind Feb 12 '14 at 19:02
  • 2
    Thoughts?, Sure: Check your api results before assuming they worked. You have six of them in the posted code, and exactly *zero* of them are validated before assuming their success. – WhozCraig Feb 12 '14 at 19:11
  • @unwind I now never cast the result of `malloc` in `C` :) Also this is a pretty funny and interesting read. http://users.powernet.co.uk/eton/c/hackerhotel.html – ajay Feb 12 '14 at 19:14
  • 1
    @ajay Great to hear it. And yeah, that's a great story. :) – unwind Feb 12 '14 at 19:16

0 Answers0