【问题标题】:XPM image memory allocationXPM 图像内存分配
【发布时间】:2015-05-03 06:18:43
【问题描述】:

我正在努力为 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 函数,它就可以工作,但我希望能够像库一样使用它。

【问题讨论】:

  • (*image).colta - nooooo! 只需 image-&gt;colta。还有don't cast the return value of malloc().
  • 我试过用image-&gt;而不是(*image).,但结果是一样的
  • image=(XPM*)malloc(sizeof(Color*) * (width * height) * cpp) 行非常可疑,因为您在其中的任何地方都没有使用sizeof(XPM)。
  • @Bogdan 是的,是一样的,只是-&gt; 更具可读性(这就是为什么我没有将其作为答案发布,而是作为评论发布的原因。)
  • @barakmanos 完全正确。这就是为什么T *p = malloc(sizeof *p); 应该优先于T *p = malloc(sizeof(T));。

标签: c pointers memory-management


【解决方案1】:
    image=(XPM*)malloc(sizeof(Color*) * (width * height) * cpp);

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-01
    • 1970-01-01
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-19
    相关资源
    最近更新 更多