This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: quick question


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 Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]