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.
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.