Hi all,
(Hope this usenet gateway works properly).
Back to this old topic again. Sorry about this. I'm just not sure if aliasing applies
in this case. Question 2.6 in the FAQ describes the common case of using one
malloc and piggy backing a char * onto it:
struct name {
int namelen;
char *namep;
};
struct name *makename(char *newname)
{
char *buf = malloc(sizeof(struct name) + strlen(newname) + 1);
struct name *ret = (struct name *)buf;
ret->namelen = strlen(newname);
ret->namep = buf + sizeof(struct name);
strcpy(ret->namep, newname);
return ret;
}
I don't believe there are aliasing issues here.
But. If you did this instead:
struct name *ret = malloc(sizeof(struct name) + strlen(newname) + 1);
char *buf = (char *)(&ret[1]);
which also seems a perfectly reasonable way of going about it, and
avoids the sizeof(struct name) which can be a little tricky in the
cases where you have several leading structs.
But you've now taken an object of type struct name and converted to a different
type pointing to the same memory. Isn't that an aliasing issue.
And if char * is a special case then what if I had used a wchar_t instead? Or
another type?
It's a bit subtle for me.
Conor.
(Hope this usenet gateway works properly).
Back to this old topic again. Sorry about this. I'm just not sure if aliasing applies
in this case. Question 2.6 in the FAQ describes the common case of using one
malloc and piggy backing a char * onto it:
struct name {
int namelen;
char *namep;
};
struct name *makename(char *newname)
{
char *buf = malloc(sizeof(struct name) + strlen(newname) + 1);
struct name *ret = (struct name *)buf;
ret->namelen = strlen(newname);
ret->namep = buf + sizeof(struct name);
strcpy(ret->namep, newname);
return ret;
}
I don't believe there are aliasing issues here.
But. If you did this instead:
struct name *ret = malloc(sizeof(struct name) + strlen(newname) + 1);
char *buf = (char *)(&ret[1]);
which also seems a perfectly reasonable way of going about it, and
avoids the sizeof(struct name) which can be a little tricky in the
cases where you have several leading structs.
But you've now taken an object of type struct name and converted to a different
type pointing to the same memory. Isn't that an aliasing issue.
And if char * is a special case then what if I had used a wchar_t instead? Or
another type?
It's a bit subtle for me.
Conor.