1
votes

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!

1
Are you allocating/deallocating a lot? That could cause heap fragmentation and limit your contiguous memory; though it seems unlikely you wouldn't be able to find 200b free.Mark Elliot
So, can you show us the code you're running?GManNickG
@pepe errno=22 is invalid argument. You will have to post code to get anything else out of SOKitsuneYMG
@Pepe: So that's like you saying "there's a problem with my car's engine" and we ask to see the car, so you give us the keys. We need to see all your code. What is sizeAllocated? What is data? What's the context? Post a full program we can reproduce the problem with. (And edit it into your question rather than as a comment.)GManNickG
@Pepe: The point was to not use your own string class. You're either programming in C or C++, pick.GManNickG

1 Answers

1
votes

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.