realloc(this, newsize)

In my code, I have a struct which can have a varying number of items. To make it simpler, I've used code similar to this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
struct SetOfNullStrings {
    char * GetItem(int Index)
    {
        char * str = (char *)this;
        while (Index--)
            str += strlen(str)+1;
        return str;
    }

    SetOfNullStrings * AddNewItem(char * NewItem, SetOfNullStrings ** Store = NULL)
    {
        // Check params
        if (!NewItem)
        {
            // report error and
            return NULL;
        }

        // Snazzy realloc()
        size_t OldSize = _msize(this),
               NewSize = OldSize+strlen(NewItem)+1;

        // realloc failed, returned null
        char * This = realloc(this, NewSize)
        if (!This)
        {
            free(this); // another risky move!

            // report error here, then
            if (Store)
                *Store = NULL;
            return NULL;
        }
        // Can't use "this" any more; it's a const pointer so we can't change it too.

        // String copying failed, handle here again
        if (strcpy_s((char *)This+OldSize, NewSize-OldSize, NewItem))
        {    
            free(This);

            // report error here again, then
            if (Store)
                *Store = NULL;
            return NULL;
        }

        // Otherwise we're good to go
        if (Store)
            *Store = This;
        return This;
    }
};

// One might use the struct like:

SetOfNullStrings * S = NULL;

// S is automatically reassigned to realloc() return... hopefully
if (!S->AddNewItem("Betsy The Cow is your item.", &S))
{
    // Error adding item... bla, bla...
}
printf(S->GetItem(0));


The code looks a bit like that. I was wondering if:
Q1: Will "this" be automatically reassigned at line 31, letting the strcpy_s() call point to the reallocated memory? A1: Nope.
Q2: Is free(this); a good move? I've seen delete this; before. A2: Works fine.

For those who don't know, _msize() returns x if you call it with malloc(x). Same with new char [x];. However, it won't work for _malloca(x) as that's stored on the stack.

EDIT:
This was solved on a chatroom I was on, I've added in the answers.
Last edited on
1
2
3
4
        char * This = realloc(this, NewSize)
        if (!This)
        {
            free(this);
Pretty unconventional stuff there.
Yeah, it was a pretty odd way of handling it. It's in the context of working with an annoying application as a DLL. It should also suit network packets, I suppose.
Topic archived. No new replies allowed.