I am struggling with allocating memory for an XPM image.
I've created my own library with the following functions:
XPM* initXPM (
unsigned int width,
unsigned int height,
unsigned int cpp,
unsigned int ncolors )
{
XPM *image;
image=(XPM*)malloc(sizeof(Color*) * (width * height) * cpp);
(*image).colta = (Color*) malloc(ncolors * sizeof(Color));
(*image).width = width;
(*image).height = height;
(*image).cpp = cpp;
(*image).ncolors = ncolors;
int i;
for (i = 0; i < ncolors; i++)
{
(*image).colta[i].pchars = (char*) malloc((cpp + 1) * sizeof(char));
}
(*image).data = (unsigned int**)malloc(height * sizeof(unsigned int*));
for (i = 0; i < height; i++)
{
(*image).data[i] = (unsigned int*) malloc(width * sizeof(unsigned int));
}
printf("init :height : %d , width :%d ncolors:%d , cpp : %d\n",(*image).height,(*image).width,(*image).ncolors,(*image).cpp);
return image;
}
The XPM structure looks like this :
typedef struct
{
unsigned int r,g,b; /* the red, green and blue components */
char *pchars; /* pointer to the character(s) combination */
} Color;
/* the number of characters for one color is contained into the XPM structure */
typedef struct
{
unsigned int width; /* width in pixels */
unsigned int height;
unsigned int cpp; /* number of characters per pixel */
unsigned int ncolors; /* how many colors we'll be using */
Color *colta; /* colors array */
unsigned int **data; /* the area that contains the image, */
/* width x height locations for */
/* indices into colta */
} XPM;
I am calling the init function in this way:
XPM *image;
image = initXPM(200,200,1,2);
I have succesfully initialized the XPM file with the values :(50,50,2,50).If i try to initialize the file with 200
instead of 50
it crashes.
I want to create a 200x200 XPM file but it breaks. Using electricfence I found out that it crashes when i set the width of the image.
How should I allocate the memory in order to be able to use it like this?
I tried to tinker a bit with the structure and it works if I declare the structure statically in my main method and send the address of the XPM image to the init function, but I want to be able to use it like a library.