Jump to content

  • Log In with Google      Sign In   
  • Create Account


Bitmap loader: Memory corruption and debugging


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
8 replies to this topic

#1 blueshogun96   Crossbones+   -  Reputation: 857

Like
0Likes
Like

Posted 15 May 2014 - 11:55 AM

Yesterday, I had to write a customized bitmap loader to replace STB.  As much as I like STB, it automatically converts 8-bit palettized textures to 24 or 32-bit.  For this particular project, this is not ideal because I need the actual 8-bit pixels and palette data from each .bmp file.  Aside from that, STB hasn't been decoding these .bmp files properly anyway.

 

My bitmap loader appears to work, however, when used to load a large set of bitmaps, there's a memory corruption problem that arises, and I have absolutely no idea what's causing it.  I really hate dumping code on you all, but I've spent a long time trying to fix this stupid thing sad.png

 

The bitmap loader:


int bitmap_open_from_memory( const unsigned char* ptr, unsigned int size, struct bitmap_t* bmp )
{
    long index = 0;
    unsigned short colours;
    int x, p = 0;
    
    /* Did we open this file? */
    if( ptr == NULL )
        return 0;
    
    memset( bmp, 0, sizeof( struct bitmap_t ) );
    
    /* Is this a bitmap file? */
    if( ptr[p++] != 'B' || ptr[p++] != 'M' )
    {
        return 0;
    }
    
    /* read in the width and height of the image, and the
     number of colours used; ignore the rest */
    p+=16;
    bmp->width = ptr[p++];
    bmp->width |= ptr[p++] << 8;
    p+=2;
    bmp->height = ptr[p++];
    bmp->height |= ptr[p++] << 8;
    p+=22;
    colours = ptr[p++];
    colours |= ptr[p++] << 8;
    p+=6;
    
    /* assume we are working with an 8-bit file */
    if( colours == 0 )
        colours = 256;
    bmp->bpp = colours/256;
    
    /* try to allocate memory */
    if( ( bmp->data = (byte*) malloc( (word)( bmp->width * bmp->height ) ) ) == NULL )
    {
        return 0;
    }
    
    /* allocate palettes */
    if( ( bmp->palette = (byte*) malloc( (word)(3*256) ) ) == NULL )
    {
        return 0;
    }
    
    /* read the palette information */
    for( index = 0; index < colours; index++ )
    {
        bmp->palette[(int)(index*3+2)] = ptr[p++] >> 2;
        bmp->palette[(int)(index*3+1)] = ptr[p++] >> 2;
        bmp->palette[(int)(index*3+0)] = ptr[p++] >> 2;
        x = ptr[p++];
    }
    
    /* read the bitmap */
    for( index = ( bmp->height-1 ) * bmp->width; index >= 0; index -= bmp->width )
        for( x = 0; x < bmp->width; x++ )
            bmp->data[(word)(index+x)] = (byte)ptr[p++];
    
    return 1;
}

void bitmap_close( struct bitmap_t* bmp )
{
    if( bmp )
    {
        if( bmp->data )
            free(bmp->data);
        if( bmp->palette )
            free(bmp->palette);
    }
}

Intended usage:

int resource_load_texture( char* strname, struct texture_t* texture )
{
    void* fileptr = NULL;
//    void* dataptr = NULL;
    int size = 0;
    struct bitmap_t bmp;
    
    /* Sanity check */
    if( !texture )
        return 0;
    
    /* Attempt to locate this file */
    /* If we find it, go ahead and lock this file and return a pointer to it. */
    if( !resource_load_raw( strname, &fileptr, &size ) )
        return 0;
    
    if( fileptr != NULL )
    {
        size_t strl = strlen(strname);
        
        /* Attempt to extract texture data from this file, but before we can do this, we need
           to find out what type of texture this is. Check for an SGI texture format. If it is,
           then use an SGI texture loading routine. If not, just use the STBI routine. */
        
        if( strname[strl-3] == '.' && strname[strl-2] == 'b' && strname[strl-1] == 'w' )
        {
            /* TODO: Write a SGI texture loader that opens from a resource */
        }
        else if( strname[strl-4] == '.' && strname[strl-3] == 'r' && strname[strl-2] == 'g' && strname[strl-1] == 'b' )
        {
            /* TODO: See above */
        }
        else
        {
            /*dataptr = stbi_load_from_memory( fileptr, size, &texture->width, &texture->height, &texture->bpp, STBI_default );*/
            
            if( !bitmap_open_from_memory( fileptr, size, &bmp ) )
                printf( "\nError reading %s\n", strname );
            
            texture->width = bmp.width;
            texture->height = bmp.height;
            texture->bpp = bmp.bpp;
        }
        
        /* Create the texture */
        texture->handle = create_texture( bmp.data, texture->width, texture->height, texture->bpp );
        
        /* Delete the data and file pointer */
        free( fileptr );
        bitmap_close(&bmp);
        //free( dataptr );
    }
    
    return 1;
}

This isn't making any sense.  When I used STB, everything was fine minus the desired effect.  Now, it crashes around the 5th or 6th use, and I have no idea why.  This sucks.  Any ideas?  Thanks.

 

Shogun.

 

EDIT: I forgot to include the actual error message:

 

"malloc: *** error for object 0x1008f5e08: incorrect checksum for freed object - object was probably modified after being freed.

*** set a breakpoint in malloc_error_break to debug"

 

Which doesn't make any sense because I've never modified any pointers after it's release.


Edited by blueshogun96, 15 May 2014 - 11:58 AM.

Follow Shogun3D on the official website: http://shogun3d.net

 

blogger.png twitter.png tumblr_32.png facebook.png


Sponsor:

#2 Vortez   Crossbones+   -  Reputation: 2689

Like
0Likes
Like

Posted 15 May 2014 - 02:11 PM

Since we dont have the full source code i can only guess (for example, what is bitmap_t), but this part seem odd to me

/* assume we are working with an 8-bit file */
    if( colours == 0 )
        colours = 256;
    bmp->bpp = colours/256;

this value shoud be 1, 4, 8, 16, 24 or 32 i beleive, not 256 or more.

 

Also, why are you doing this?

bmp->width |= ptr[p++] << 8;

Another this that dosen't help is you are incrementing the pointer value each line instead of using fixed offset so it's hard to tell where you are reading value from in the header.

 

Also, remember that bitmap must be 4 bytes aligned. So this line is probably wrong

    for( index = ( bmp->height-1 ) * bmp->width; index >= 0; index -= bmp->width )


Edited by Vortez, 15 May 2014 - 02:19 PM.


#3 fastcall22   Crossbones+   -  Reputation: 4155

Like
0Likes
Like

Posted 15 May 2014 - 02:22 PM

A few questions:
  • In what way was STB decoding your .bmp files incorrectly?
  • How do you notice memory corruption?
  • Are all of your .bmp files 8-bit? Or are there some with a different bpp?
  • Have you consulted the BMP file format specification? It seems that you're making some potentially dangerous assumptions about your bmp files.
  • What is the "desired effect"? I'm assuming the palette swapping effect, since you mention that you need the palette data. Since we're dealing with memory corruption, you should suspect any routine that might modify these objects.
"Object was probably modified after being freed" could mean that you're not properly managing object sharing. That is, you're freeing an object where there might still be references to that object. If a different object is allocated in its place and the old object is modified, then that could be the source of your corruption. A smart pointer could help here as a quick-fix, although proper object lifetime management would solve the problem.
c3RhdGljIGNoYXIgeW91cl9tb21bMVVMTCA8PCA2NF07CnNwcmludGYoeW91cl9tb20sICJpcyBmYXQiKTs=

#4 Vortez   Crossbones+   -  Reputation: 2689

Like
0Likes
Like

Posted 15 May 2014 - 02:36 PM

After re-reading your post i understand a little better, but it still look wrong to me. If i may suggest a thing or two..

 

i would replace

    /* Is this a bitmap file? */
    if( ptr[p++] != 'B' || ptr[p++] != 'M' )
    {
        return 0;
    }

with

if(strncmp((char*)ptr[0], "BM", 2) != 0){
    return 0
}

Then, more importantly:

BITMAPINFOHEADER *lpbi = (BITMAPINFOHEADER*)ptr[14];

bmp->width = lpbi->biWidth;
bmp->height = lpbi->biHeight;
bmp->bpp = lpbi->biBitCount;
if(bpp != 8){
    return false;
}


I also made this little helper class to help me deal with bitmap aligment madness some time ago, i guess you could adapt it to your code if you feel the need to. Although it's not bad if your dealing with only 8 bpp bitmaps, doing 1, 4, 8 and 16 bpp bitmaps all at once was crazy...

 

http://en.wikipedia.org/wiki/BMP_file_format

http://msdn.microsoft.com/en-us/library/windows/desktop/dd183375%28v=vs.85%29.aspx


Edited by Vortez, 15 May 2014 - 02:50 PM.


#5 blueshogun96   Crossbones+   -  Reputation: 857

Like
0Likes
Like

Posted 15 May 2014 - 02:38 PM

 

Since we dont have the full source code i can only guess (for example, what is bitmap_t), but this part seem odd to me

/* assume we are working with an 8-bit file */
    if( colours == 0 )
        colours = 256;
    bmp->bpp = colours/256;

this value shoud be 1, 4, 8, 16, 24 or 32 i beleive, not 256 or more.

 

Also, why are you doing this?

bmp->width |= ptr[p++] << 8;

Another this that dosen't help is you are incrementing the pointer value each line instead of using fixed offset so it's hard to tell where you are reading value from in the header.

 

Also, remember that bitmap must be 4 bytes aligned. So this line is probably wrong

    for( index = ( bmp->height-1 ) * bmp->width; index >= 0; index -= bmp->width )

 

1. This bitmap loader was written to only read 8-bit textures.  Also, when the texture is 8-bits wide, the bit depth field will be either 0 or 256.

 

The structure is defined as follows:

/* 8-bit palettized bitmap texture */
struct bitmap_t
{
    unsigned short width, height;   /* Dimensions */
    unsigned char* palette;         /* Colour palette */
    unsigned char* data;            /* Pixel data */
    unsigned int bpp;               /* Bits per pixel */
};

2. The reason it's done that way is because I'm reading the header byte by byte.  The width, height, and bpp fields are 16-bits wide, so bitwise operations are used to get the full 16-bit value.  If you don't understand where this is coming from, take a look at the original from which this function was derived:

/* Skip bytes in a file */
void fskip( FILE* fp, int bytes )
{
    int i = 0;
    
    while( i < bytes )
        fgetc(fp);
}

int bitmap_open( char* filename, struct bitmap_t** bmp )
{
    FILE* fp = fopen( filename, "rb" );
    long index;
    unsigned short colours;
    int x;
    
    /* Did we open this file? */
    if( fp == NULL )
        return 0;
    
    /* Is this a bitmap file? */
    if( fgetc(fp) != 'B' || fgetc(fp) != 'M' )
    {
        fclose(fp);
        return 0;
    }
    
    /* read in the width and height of the image, and the
     number of colors used; ignore the rest */
    fskip(fp,16);
    fread(&(*bmp)->width, sizeof(word), 1, fp);
    fskip(fp,2);
    fread(&(*bmp)->height,sizeof(word), 1, fp);
    fskip(fp,22);
    fread(&colours, sizeof(word), 1, fp);
    fskip(fp,6);
    
    /* assume we are working with an 8-bit file */
    if( colours == 0 )
        colours = 256;
    
    /* try to allocate memory */
    if( ( (*bmp)->data = (byte *) malloc( (word)( (*bmp)->width * (*bmp)->height ) ) ) == NULL )
    {
        fclose(fp);
        return 1;
    }
    
    /* allocate palettes */
    if( ( (*bmp)->palette = (byte *) malloc( (word)(3*256) ) ) == NULL )
    {
        fclose(fp);
        return 1;
    }
    
    /* read the palette information */
    for( index = 0; index < colours; index++ )
    {
        (*bmp)->palette[(int)(index*3+2)] = fgetc(fp) >> 2;
        (*bmp)->palette[(int)(index*3+1)] = fgetc(fp) >> 2;
        (*bmp)->palette[(int)(index*3+0)] = fgetc(fp) >> 2;
        x=fgetc(fp);
    }
    
    /* read the bitmap */
    for( index = ( (*bmp)->height-1 ) * (*bmp)->width; index >= 0; index -= (*bmp)->width )
        for( x = 0; x < (*bmp)->width; x++ )
            (*bmp)->data[(word)(index+x)] = (byte)fgetc(fp);
    fclose(fp);
    
    return 1;
}

3. Not quite; an 8-bit palettized bitmap is different (as well as a lesser 16 colour bitmap, but that's a whole different story).  The data is one byte wide per pixel.  If I were expanding the pixel data to 32-bit, that would be the case.  This bitmap loader is based off of an existing one from a game I once ported from DOS to a console, so I know it works.

 

Shogun.

 

EDIT: Responding to new replies in just a minute...


Edited by blueshogun96, 15 May 2014 - 02:40 PM.

Follow Shogun3D on the official website: http://shogun3d.net

 

blogger.png twitter.png tumblr_32.png facebook.png


#6 Vortez   Crossbones+   -  Reputation: 2689

Like
0Likes
Like

Posted 15 May 2014 - 02:53 PM

Having worked with bitmap for 2 months straigh not long ago, i can garanty you, they are 4 bytes aligned (per LINE), regardless of the bit per pixels.

 

Ex: if you have a 8 bit bitmap that is 255 pixels width, the size of 1 line (or row) of pixels should be 256 bytes.

 

Im pretty sure the memory problem your having is a simple buffer overflow, but without debugging, im just guessing.


Edited by Vortez, 15 May 2014 - 03:09 PM.


#7 blueshogun96   Crossbones+   -  Reputation: 857

Like
0Likes
Like

Posted 15 May 2014 - 03:00 PM

A few questions:

  • In what way was STB decoding your .bmp files incorrectly?
  • How do you notice memory corruption?
  • Are all of your .bmp files 8-bit? Or are there some with a different bpp?
  • Have you consulted the BMP file format specification? It seems that you're making some potentially dangerous assumptions about your bmp files.
  • What is the "desired effect"? I'm assuming the palette swapping effect, since you mention that you need the palette data. Since we're dealing with memory corruption, you should suspect any routine that might modify these objects.
"Object was probably modified after being freed" could mean that you're not properly managing object sharing. That is, you're freeing an object where there might still be references to that object. If a different object is allocated in its place and the old object is modified, then that could be the source of your corruption. A smart pointer could help here as a quick-fix, although proper object lifetime management would solve the problem.

 

 

1. Data is not aligned properly AFAIK.  I'll attach a screenshot of it.  

 

Screen Shot 2014-05-15 at 1.43.20 PM.png

 

This happens with certain textures though, not all of them.  I have some from "The Lost Garden" and others coming from Andre Lamothe's books.  They are likely to be formatted differently, because textures from the former don't load properly, while those from the latter do, respectively.

2. During the loading phase, the game will crash around the time the 5th or 6th texture is created.  The crash happens when malloc is called.

3. All textures are 8-bit. Every last one.

4. That could be the case.  If so, then I'll either need to write a better loader, or convert them to a different format altogether.  Since I'm not using Windows, and my game is cross platform, I can't rely on Window's GDI to load it for me.

5. Yes, bingo.  Palette swapping, etc. is a feature I intend to use for this game in particular, since I am aiming to write a true 16-bit style game to resemble the Sega Genesis and Super Nintendo era (not just pixelated).

 

I'm not saying that it isn't the problem, but I have the feeling that I've written beyond one of the pointers I've manually allocated.  This error has manifested itself before, and I am quite sure that is where I am screwing up.  If my theory in response #4 is correct, I might end up just using .tga instead.

 

After re-reading your post i understand a little better, but it still look wrong to me. If i may suggest a thing or two..

 

i would replace

    /* Is this a bitmap file? */
    if( ptr[p++] != 'B' || ptr[p++] != 'M' )
    {
        return 0;
    }

with

if(strncmp((char*)ptr[0], "BM", 2) != 0){
    return 0
}

Then, more importantly:

BITMAPINFOHEADER *lpbi = (BITMAPINFOHEADER*)ptr[14];

bmp->width = lpbi->biWidth;
bmp->height = lpbi->biHeight;
bmp->bpp = lpbi->biBitCount;
if(bpp != 8){
    return false;
}


I also made this little helper class to help me deal with bitmap aligment madness some time ago, i guess you could adapt it to your code if you feel the need to. Although it's not bad if your dealing with only 8 bpp bitmaps, doing 1, 4, 8 and 16 bpp bitmaps all at once was crazy...

 

http://en.wikipedia.org/wiki/BMP_file_format

http://msdn.microsoft.com/en-us/library/windows/desktop/dd183375%28v=vs.85%29.aspx

 

Thanks, I'll look into this.  Also, keep in mind that I'm writing this game in 100% pure C, so I'll be leaving out certain C++ features.

 

Shogun.


Follow Shogun3D on the official website: http://shogun3d.net

 

blogger.png twitter.png tumblr_32.png facebook.png


#8 krinosx   Members   -  Reputation: 500

Like
0Likes
Like

Posted 15 May 2014 - 03:03 PM

If I can throw my coin... ( back in original question about the 'free' problem )

 

I had some problems with 'freeing a pointer twice'.. I mean... are you sure your code is not trying to free a already freed pointer?

void bitmap_close( struct bitmap_t* bmp )
{
    if( bmp )
    {
        if( bmp->data )
            free(bmp->data);
        if( bmp->palette )
            free(bmp->palette);
    }
}

I mean... its hard to assume that " bmp->data " is FALSE in that case... I think its safe to check against NULL or nullptr in your IF statements....

 

You can fast figure it out if you does not invoke 'bitmap_close' and test your software... you may generate some memory leak but if the error stops you change the IF statements and check again...

 

Edit: Fixing some typo


Edited by krinosx, 15 May 2014 - 03:04 PM.


#9 gdunbar   Crossbones+   -  Reputation: 890

Like
0Likes
Like

Posted 16 May 2014 - 09:29 AM

 

I'm not saying that it isn't the problem, but I have the feeling that I've written beyond one of the pointers I've manually allocated.  This error has manifested itself before, and I am quite sure that is where I am screwing up.  If my theory in response #4 is correct, I might end up just using .tga instead..

 

 

Seems most likely. Here are the steps I would take:

 

1) Get a consistent reproduction of the crash. Writing a simple test app that simply loads and unloads a bitmap over and over might be a good start. Keep adding stuff until you can repro, but the simpler the better.

2) Once you have that, see if you can figure out why it is breaking. If (as seems like a reasonable explanation), you are writing past allocated memory, try allocating the buffer slightly bigger, and then (right before you free it) see what got written past the expected end. Set a memory breakpoint on that location and figure out what code is going wrong. Etc.

 

If you can't get a consistent repro, things are a little harder. Again, get a test program that crashes every time, if not in the same place. Randomly loading bitmaps until boom. Then, start removing code until it stops crashing. The last thing you removed was your bad actor.

 

Good luck, memory corruption bugs can be very frustrating.

 

Geoff






Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS