开发者

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!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜