• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
blueshogun96

Bitmap loader: Memory corruption and debugging

8 posts in this topic

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
1

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites

 

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
0

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites

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.  

 

[attachment=21561: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.

0

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites

 

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

0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0