XPM图像内存分配

时间:2015-03-02 19:07:26

标签: c pointers memory-management

我正在努力为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;

我以这种方式调用init函数:

XPM *image;

    image = initXPM(200,200,1,2);

我已成功初始化XPM文件,其值为:(50,50,2,50)。如果我尝试使用200而不是50初始化文件,则会崩溃。
我想创建一个200x200 XPM文件,但它会中断。使用电子栅栏我发现当我设置图像的宽度时它会崩溃 我应该如何分配内存以便能够像这样使用它? 我尝试对结构进行修改,如果我在main方法中静态声明结构并将XPM图像的地址发送到init函数,它就可以工作了,但我希望能够像库一样使用它。

1 个答案:

答案 0 :(得分:0)

    image=(XPM*)malloc(sizeof(Color*) * (width * height) * cpp);

显然是错误的,但是由于这为除了最小的图像以外的所有图像分配了太多的内存,因此它不会导致您提到的崩溃。尽管如此

  • image = malloc(sizeof *image);将是正确的分配

  • initXPM(200, 200, 2, 50);不会在我的系统上崩溃

  • 您应该使用调试器(例如gdb)而不是efence来分析问题。