I have this class, with 3 char-arrays that are initialized like this:
After that, I have a constructor, that copies values to these from a file (read until \n), which ALWAYS work perfectly. I am 100% sure this function is not wrong, since it has worked before, and I haven't changed it. This function copies everything to its correct place.Code:this->name = (char*) malloc(64); this->type = (char*) malloc(64); this->item_class = (char*) malloc(64);
Now. My problem is:
I have a function that enchants a weapon (warhammer in this case), and because of that, appends the enchantments name to the weapons name (this->name).
warhammer <enchantments name>
These enchantment names are less than 20 characters long. And the weapon names are less than 20 characters long aswell.
I have a warhammer that I enchant, and when it gets some enchants (not all, some enchants work fine) like " of minor striking" or " of minor intellect", somehow my this->item_class gets overwritten and now says ing or lect.
This shouldnt happen, since I have already allocated memory for up to 64 chars.
The only thing the enchant function does, is appends the enchantments name to this->name.
this->item_class remains untouched.
Why does this happen?
I make it a rule to allocate ATLEAST 64 bytes of memory for all strings, and I have nothing in my program that takes up more than 15-20 bytes on its own.
Add enchant and weapon name together and you still only get at most a 40-byte string.
P.S. this->item_class contains a small string, such as exotic, two-handed or ranged.
I use strcat to append the enchantments name.