0

I was writing a C program that reads the width and heights of a bmp image following (http://smsoftdev-solutions.blogspot.com.au/2014/07/code-for-reading-bmp-image-files.html). But I've met an error in terminal, it shows that:

i './a.out' terminated by signal SIGSEGV (Address boundary error)

I did some googling, they mention it's accessing extra memory problem, but I can't really find that in my code, any suggestion would be appreciated

#include <stdio.h>

struct __attribute__((__packed__)) BitmapHeader
{
    int width; 
    int height; 
};


void loadBmp(char* filePath, struct BitmapHeader bmpHeaderInfo){
    FILE* filePtr = fopen(filePath, "rb");

    unsigned char header[54];
    fread(header, sizeof(unsigned char), 54, filePtr);
}

int main(){
    char path2BMP[] = "/cup.bmp";
    struct BitmapHeader bmpHeaderInfo = {0};
    loadBmp(path2BMP, bmpHeaderInfo);
    return 0;
}
libra
  • 673
  • 1
  • 10
  • 30
  • 5
    First things first, you understand that your code is looking for `cup.bmp` in the ***root*** folder of your file system (not your user-root foler, rather **the** root folder), and that failure to open it is utterly ignored, code marching on with a null pointer then-passed to `fread`. Secondly, `loadBmp`, even if it worked, does *nothing* with the caller's `bmpHeaderInfo`, as it is passed *by-value*, not address, from `main()` (not that it matters, even the by-value copy remains untouched in the function). – WhozCraig Mar 31 '16 at 07:23
  • 4
    You need to add code that checks if `fopen()` succeeds, since the crash is likely because it does not succeed. Print out an error if it `fopen()` fails. so you'll know about it failing. use the `perror()` function to print the error, as that will also print the reason fopen() failed. – nos Mar 31 '16 at 07:29
  • @WhozCraig, Thx!, i change the path to my bmp and the error is gone now, but how do i pass the instance of bmpHeaderInfo to loadbmp by address? i'm extremely new to c, sry for the noob question. – libra Mar 31 '16 at 07:31
  • 2
    hit the web (this site as well) for "C language parameter pass by reference", examples [such as **this**](http://stackoverflow.com/questions/1919718/pass-by-reference-in-c). – WhozCraig Mar 31 '16 at 07:33
  • @WhozCraig thank you!, all set now XD – libra Mar 31 '16 at 07:38
  • @nos, thx for your suggestion!< added – libra Mar 31 '16 at 07:38
  • Since you are trying to parse a BMP file, https://stackoverflow.com/questions/17967480/parse-read-bitmap-file-in-c answers this question as well, and it can be marked as solved as a duplicate. – sashoalm Mar 31 '16 at 12:08

0 Answers0