Pergunta

I am having to work with someone else's code, so I am not entirely in control over what I can change but I am wondering why I am getting this error and would appreciate any suggestions. This code is in the part that I can't change but I need to make sure the part I wrote (StringRef class) works.

The error it gives me is 'Heap block at X modified at Y past requested size of 28'. If I change the existing code which is using realloc to malloc it kicks the can down the road a bit and loads a few more values into the array. Here are the lines in question. I can't include all the code as it is too extensive. Is this enough info to diagnose what I am doing wrong?

struct StringList
{
    StringRef *elements;
    unsigned int count;
};

.....

// Append the given StringRef to the list.
bool StringListAppend(StringList& self, StringRef p_string)
{

    StringRef *t_new_elements;
    t_new_elements = (StringRef *)realloc(self.elements, (self.count + 1) * sizeof(StringRef *));
    if (t_new_elements == NULL)
        return false;

    self.elements = t_new_elements;
    std::cout<<self.count<<"\n";
    // Initialize and assign the new element.
    StringInitialize(self.elements[self.count]);
    if (!StringAssign(self.elements[self.count], p_string))
        return false;

    // We've successfully added the element, so bump the count.
    self.count += 1;

    return true;
}

vs

StringRef *t_new_elements;
t_new_elements = (StringRef *)malloc((self.count + 1) * sizeof(StringRef *));

for the line with realloc averts the problem a little further.

Foi útil?

Solução

sizeof(StringRef *) should be sizeof(StringRef)

You could avoid this error by using this idiom:

ptr = realloc(old_ptr, n_elements * sizeof *ptr);

when the number of bytes to allocate is determined based on the type of the variable that holds the returned pointer; it doesn't require you to repeat anything and thereby introduce a discrepancy.

As to why changing realloc to malloc slightly moves the point at which the program crashes... undefined behaviour is undefined :)

Outras dicas

Lets say you wish to allocate some memory. You should use malloc (stores memory on heap uninitialized) or calloc(stores initializes all elements to 0). Explained more Here!

Realloc extends the length of your allocated memory. So you need to allocate some before you can extend it. (dont neeed to, but it is good coding practice to do so) Realloc

I would suggest looking up more on memory allocation because abusing it can greatly reduce efficiency and must be treated with precaution, like: you should always free memory that you have allocated at the end of your program!

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top