Я борюсь с распределением памяти для изображения XPM.
Я создал свою собственную библиотеку со следующими функциями:Распределение памяти памяти XPM
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;
}
XPM выглядит следующим образом:
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;
Я звоню функцию инициализации следующим образом:
XPM *image;
image = initXPM(200,200,1,2);
Я успешно инициализировал файл XPM со значениями: (50,50,2,50). Если я попытаюсь инициализировать файл 200
вместо 50
сбой.
Я хочу создать файл XPx 200x200, но он сломается. Используя electfence, я обнаружил, что он падает, когда я устанавливаю ширину изображения.
Как я могу выделить память, чтобы использовать ее так?
Я попытался немного поработать со структурой, и она работает, если я объявляю структуру статически в моем основном методе и отправляю адрес образа XPM в функцию init, но я хочу иметь возможность использовать его как библиотеку.
'(* изображение) .colta' - *** nooooo! *** Просто сделайте' image-> colta'. И [не оставляйте возвращаемое значение 'malloc()'] (https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858). –
Я попытался использовать 'image->' вместо '(* image) .', но это тот же результат. –
Линия' image = (XPM *) malloc (sizeof (Цвет *) * (ширина * высота) * cpp) 'очень подозрительно из-за того, что вы не используете' sizeof (XPM) 'нигде в нем. –