Strict aliasing and Q2.6 in the FAQ

Discussion in 'C Programming' started by Carveone, Sep 19, 2011.

  1. Carveone

    Carveone

    Joined:
    Sep 19, 2011
    Messages:
    1
    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.
    Carveone, Sep 19, 2011
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Paul Brettschneider

    char and strict aliasing

    Paul Brettschneider, Jul 17, 2008, in forum: C++
    Replies:
    4
    Views:
    423
    James Kanze
    Jul 18, 2008
  2. Francois Duranleau

    Strict aliasing and buffer handling

    Francois Duranleau, Jun 20, 2011, in forum: C++
    Replies:
    20
    Views:
    1,561
    Alf P. Steinbach /Usenet
    Jun 22, 2011
  3. Conor F

    Strict aliasing and Q2.6 in the FAQ

    Conor F, Sep 19, 2011, in forum: C Programming
    Replies:
    7
    Views:
    520
    Conor F
    Sep 20, 2011
  4. Maxim Fomin

    Union and strict aliasing

    Maxim Fomin, Jul 28, 2012, in forum: C Programming
    Replies:
    4
    Views:
    456
    Maxim Fomin
    Aug 2, 2012
  5. Xavier Roche
    Replies:
    3
    Views:
    93
    James Kuyper
    Mar 25, 2014
Loading...

Share This Page