加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

将int成员添加到C结构会导致段错误

发布时间:2020-12-16 10:53:58 所属栏目:百科 来源:网络整理
导读:我还在学习C,并开始使用它来生成图像.我无法弄清楚为什么我的一个程序是segfaulting.这是源代码,减少到40行: #include stdio.h#include stdlib.hstruct color { unsigned char r,g,b;};struct image { int w,h/*,o*/; struct color **data;};int main() { /
我还在学习C,并开始使用它来生成图像.我无法弄清楚为什么我的一个程序是segfaulting.这是源代码,减少到40行:

#include <stdio.h>
#include <stdlib.h>
struct color {
        unsigned char r,g,b;
};
struct image {
        int w,h/*,o*/;
        struct color **data;
};
int main() {
        // Declarations
        int x,y;
        struct color *black;
        struct image *img;
        // Set up color black
        black = (struct color *) malloc(sizeof(struct color *));
        black->r = 0;
        black->g = 0;
        black->b = 0;
        // Set up image img
        img = (struct image *) malloc(sizeof(struct image *));
        img->w = 1;
        img->h = 1;
        /*img->o = 0;*/
        img->data = (struct color **) malloc(img->h * sizeof(struct color *));
        for (y = 0; y < img->h; y++) {
                img->data[y] = (struct color *) malloc(img->w * sizeof(struct color));
        }
        // Fill in img with black
        for (x = 0; x < img->w; x++) {
                for (y = 0; y < img->h; y++) {
                        img->data[y][x].r = black->r;
                        img->data[y][x].g = black->g;
                        img->data[y][x].b = black->b;
                }
        }
        // Free black
        free(black);
        // Free img
        for (y = 0; y < img->h; y++)
                free(img->data[y]);
        free(img->data); // Segfaults
        free(img); // Also segfaults
        return 0;
}

它编译并运行正常(在Ubuntu和使用Cygwin的Vista上使用gcc),但是取消注释处理img-> o的两行会打破它.我有一种感觉它与this previous question有关,但我正在考虑所有需要进行摩托车操作的东西(我认为).任何帮助,将不胜感激.

解决方法

您的malloc语句中存在错误.你正在使用指针而不是结构.这只给你4个字节的内存,而不是你的struct所需的实际大小.

black = malloc(sizeof(*black));

为指针分配内存时,需要为指向的事物分配内存,而不是指针的类型.如果您只是如图所示编写sizeof(* black),即使黑色类型发生变化,您也将始终获得正确的类型.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读