Pubby
Pubby

Reputation: 53017

Realloc returning null?

I allocate some memory with malloc - about 128 bytes.

Later on, I call realloc with about 200 bytes, but it's returning null!

It returns a valid pointer if I do free, and then another malloc, however I would like to use realloc.

What could explain this behavior (I clearly am not running out of memory)? Is this valid behavior?

Code bits:

//class constructor
size = 0;

sizeAllocated = DEFAULT_BUFFER_SIZE; //64

data = (char*)malloc(sizeAllocated * sizeof(char)); //data is valid ptr now, I've checked it

data[0] = '\0';

//later on:
//append function
bool append(char** data, const char* str, size_t strLen) {
  if((size + strLen) >= sizeAllocated) {
     sizeAllocated += strLen + 1 + BUFFER_ALLOCATION_STEP;
     char* temp = realloc(*data, sizeAllocated * sizeof(char));
     if(temp)
        *data = temp;

     return( temp != NULL );

}

EDIT: fixed. I was overloading the << operator for my class, and had it return *this instead of void. Somehow this was screwing everything up! If anyone could explain why this happen, it would be nice!

Upvotes: 1

Views: 2554

Answers (1)

Windows programmer
Windows programmer

Reputation: 8065

Since the following comment was added to the question

data = (char*)realloc(data, (size_t)(sizeAllocated * sizeof(char)));

if I replace sizeAllocated with a constant that is same value, it reallocs correctly

Now we can figure out what happened. You replaced sizeAllocated with a constant that DID NOT have the same value. For debugging purposes, add a statement that will output the value of sizeAllocated and you will be surprised.

Upvotes: 1

Related Questions