0

I am currently working on a simple server implemented in C. Processing jpg files works fine, btu png's give me a segmentation fault. I never get past this chunk of code. Why this might be?

fseek (file , 0 , SEEK_END);
lSize = ftell (file);
rewind (file);

Thanks.

Cade Roux
  • 88,164
  • 40
  • 182
  • 265
Krzysiek
  • 1,487
  • 4
  • 19
  • 28
  • Use a debugger and see where it segfaults. – m0skit0 May 02 '12 at 00:37
  • This code looks OK to me, assuming file is not NULL, and your file is small enough that you don't run into 32 bit limits. I'd suggest running your code under valgrind and/or the debugger to see whats really going wrong. – Michael Anderson May 02 '12 at 00:38
  • 1
    The problem is almost certainly *not* occurring in the code you posted. Q: are you reading the file prior to this code? It smells like you're doing a "read" that's overwriting a buffer. Buffer overruns often occur in one place ... but the damage they cause only shows up in a later, in a *different* place. – paulsm4 May 02 '12 at 00:41
  • Well, the thing is, though, that jpg processing is the same code and it works for jpg. The file is not NULL; I check it earlier using an if statement. – Krzysiek May 02 '12 at 00:47
  • There is probably something in your PNG handling code which is over-running whatever that `FILE*` is pointing to. – Mark Nunberg May 02 '12 at 01:01
  • Oh, boy... I think I fixed it. Can a seg fault occur because I have too many stack-allocated variables? I was allocating large arrays on stack and now that I reduced them, the problem is gone... – Krzysiek May 02 '12 at 01:03
  • @Rafcio What stack size? We'd need to know the platform to tell you how to control the stack size. http://stackoverflow.com/questions/1847789/segmentation-fault-on-large-array-sizes – Cade Roux May 02 '12 at 01:46
  • 1
    Q: Can a seg fault occur because I have too many stack-allocated variables? A: Yes :) http://stackoverflow.com/questions/199747/how-to-detect-possible-potential-stack-overflow-problems-in-a-c-c-program – paulsm4 May 02 '12 at 18:36

1 Answers1

2

It's far more likely that you were accessing those arrays in a problematic fashion. Check the logic in your buffering code. Make sure you have your buffer sizes #define'd in a central location, rather than hardcoding sizes and offsets. You made it quit crashing, but if you missed an underlying logic error, you may run into mysterious problems down the road when you change something else. It is probably worth your time to deliberately break the program again and figure out WHY it's broken. As others have suggested, a debugger would be an excellent idea at this point. Or post a more complete example of your code.

coydog
  • 111
  • 4