Re: quick question

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Jim Stapleton wrote:
char *superstring = (char*)malloc(sizeof(int) * 2 + sizeof(char) * string_size);

string lenght: (int)*(superstring - sizeof(int))
string allocated: (int)*(superstring - sizeof(int) * 2)

Suggestion:

    typedef struct {
        size_t allocated, length;
        char contents[1];
    } SuperString;

    SuperString *superstring =
        malloc(offsetof(SuperString,contents) + string_size);

Incidentally, C and C++ both guarantee sizeof(char)==1, and in C it's considered good practice to omit explicit casts from (void*) in this situation, since the redundancy can be a source of error. (But in C++ you can't omit them.)

-- Ben


[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux