Why this doesn't work?

Hello.
I made a BMP reader which works in the function, but crashes in int main(). Seems that data pointer somehow gets deleted.
My code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

bool readBMP(string filename, unsigned char * data, int & sz)
{
    unsigned char header[54];
    int width;
    int height;
    int fsize;

    FILE *fl;

    fl = fopen(filename.c_str(), "rb");

    if(!fl) return false;

    fread(header, 1, 54, fl);

    if(header[0]!='B' || header[1]!='M') return false;

    width = *(int*)&header[18];
    height = *(int*)&header[22];

    fsize=width*height*3;

    cout<<"Size: "<<fsize<<endl;
    cout<<"Width: "<<width<<"\nHeight: "<<height<<"\n";

    if(data) delete [] data;
    data= new unsigned char[fsize];

    fread(data,1,fsize,fl);

    fclose(fl);

    sz=fsize;

    //when printing 'data' content here, it works great.

    for(int i=0; i<fsize; i++) 
    {
        cout<<(int)data[i]<<" ";
    }

    return true;
}

int main()
{
    unsigned char *data;
    int fsize;

    readBMP("bmp2.bmp", data, fsize);

    cout<<"fsize="<<fsize<<endl;
    cout<<"Trying to print data.\n";

    for(int i=0; i<fsize; i++) 
    {
        cout<<(int)data[i]<<" ";  //Crash!!
    }

    //delete [] data;

    return 0;
}
line 56: `data' is uninitialized
line 33: `data' was passed by copy, the modifications would not be visible outside of the function, memory leak.
Topic archived. No new replies allowed.