Strict aliasing and Q2.6 in the FAQ

Joined
Sep 19, 2011
Messages
1
Reaction score
0
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,992
Messages
2,570,220
Members
46,807
Latest member
ryef

Latest Threads

Top