分配给元素结构和存储于一体的malloc [英] allocate struct and memory for elements in one malloc

查看:84
本文介绍了分配给元素结构和存储于一体的malloc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相信这是一个基本的问题,但我一直没能找到这是否是一个合法的内存分配策略与否。我将数据从文件中读取,我在一个结构填充。成员的大小是可变的每次读,所以我的结构元素的指针,像这样

I am sure this is a basic question but I haven't been able to find whether or not this is a legitimate memory allocation strategy or not. I am reading in data from a file and I am filling in a struct. The size of the members are variable on each read so my struct elements are pointers like so

struct data_channel{
    char *chan_name;
    char *chan_type;
    char *chan_units;
};

所以看完我才弄清楚每个字符串的大小是这样我就可以分配给他们的记忆我的问题是,我可以分配内存的结构和字符串都在同一个malloc和然后填写指针在哪?

So before reading I figure out what the size of each string is so I can allocate memory for them my question is can I allocate the memory for the struct and the strings all in one malloc and then fill the pointer in?

说chan_name的大小为9,chan_type 10和chan_units 5.因此,我想分配,做这样的事情。

Say the size of chan_name is 9, chan_type 10, and chan_units 5. So I would allocate the and do something like this.

struct data_channel *chan;

chan = malloc(sizeof(struct data_channel) + 9 + 10 + 5);
chan->chan_name = chan[1];
chan->chan_type = chan->chan_name + 9;
chan->chan_units = chan->chan_type + 10;

所以我读了几个关于内存对齐的文章,但我不知道,如果做上述问题或不是,也可能有什么样的意想不到的后果。我已经在我的code语言实现它,它似乎很好地工作。我只是不希望有把所有这些指针的跟踪,因为在现实中我的每个结构的有7个要素,我可以有向上100个频道。当然,这意味着700指针加上每个指针结构中以总800。我也必须制定一种方法来释放他们。我也想这种策略适用于字符串,而我则需要有指针数组的数组。我没有任何的结构,现在,将混合数据类型会是一个问题,但我可能会是一个问题吗?

So I read a couple of articles on memory alignment but I don't know if doing the above is a problem or not or what kind of unintended consequences it could have. I have already implemented it in my code and it seems to work fine. I just don't want to have to keep track of all those pointers because in reality each of my structs has 7 elements and I could have upwards of 100 channels. That of course means 700 pointers plus the pointers for each struct so total 800. The I also have to devise a way to free them all. I also want to apply this strategy to arrays of strings of which I then need to have an array of pointers to. I don't have any structures right now that would mix data types could that be a problem but I might could that be a problem?

推荐答案

如果 chan_name 是一个8个字符的字符串, chan_type 是9个字符的字符串, chan_units 是一个4个字符的字符串,那么是的,它会在你修复分配给 chan_name 。

If chan_name is a 8 character string, chan_type is a 9 character string and chan_units is a 4 character string, then yes it will work fine when you fix the compilation error you have when assigning to chan_name.

如果您对分配结构加上足够的内存中的所有字符串(包括其字符串结束),那么也没关系使用这种方法。也许不建议所有,但它会工作。

If you allocate enough memory for the structure plus all the strings (including their string terminator) then it's okay to use such a method. Maybe not recommended by all, but it will work.

这篇关于分配给元素结构和存储于一体的malloc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆