jdscardoso
jdscardoso

Reputation: 291

C - free() error

This is my function where I am debugging:

boolean
adin_memory(char* buffer, int size_chunck, int end_flag){
    global_buffer = mymalloc(size_chunck*sizeof(char)); //3
    global_buffer = buffer;

    real_data= (SP16 *)mymalloc(size_chunck*sizeof(SP16));  //3
    memcpy(real_data,global_buffer,size_chunck);

    free(global_buffer); //ERROR

    pos_escrita += size_chunck;

    global_size = size_chunck;
    global_end_flag = end_flag;
    return TRUE;
}

And this is mymalloc function:

void *
mymalloc(size_t size)
{
  void *p;
  if ( (p = malloc(size)) == NULL) {
#if defined(_WIN32) && !defined(__CYGWIN32__)
    jlog("Error: mymalloc: failed to allocate %Iu bytes\n", size);
#else
    jlog("Error: mymalloc: failed to allocate %zu bytes\n", size);
#endif
    *((char*)0) = 0 ; //###ARL provoca um exception
    exit(1);
  }
  return p;
}

I am getting this error when free() functions is called. Why? enter image description here

Upvotes: 0

Views: 97

Answers (3)

milevyo
milevyo

Reputation: 2184

from first sight:

//you allocate memory and store it in global_buffer
global_buffer = mymalloc(size_chunck*sizeof(char)); //3

// you overwrite global_buffer by a new value of buffer
global_buffer = buffer;

// global_buffer no more hold the address of memory allocated
// but you still want to free it
...
free(global_buffer);

Upvotes: 1

R Sahu
R Sahu

Reputation: 206737

Problems that I see:

global_buffer = mymalloc(size_chunck*sizeof(char)); //3
global_buffer = buffer;

That results in a memory leak. The value returned by mymalloc is now lost.

real_data= (SP16 *)mymalloc(size_chunck*sizeof(SP16));  //3
memcpy(real_data,global_buffer,size_chunck);

free(global_buffer); //ERROR

That will be a problem depending on how buffer was defined. The above statement is equivalent to:

free(buffer);

It's hard to say why that is an error without seeing how the function was called. It's hard to suggest what should be changed without understanding the bigger picture. To be more specific, it is not clear why you needed to use:

global_buffer = buffer;

Upvotes: 3

Jiminion
Jiminion

Reputation: 5168

You are reassigning global_buffer to 'buffer' which is an address unknown to the heap. That's why you are getting an error. Don't do the second assignment to global_buffer.

Also, you should check for an earlier error so you don't accidentally try to free the null pointer.

Upvotes: 1

Related Questions