Jack
Jack

Reputation: 16724

Can't free() value allocated by malloc() in another function

I have a C function, something like this:

void foo(char ** out) {
     *out = malloc(computedsize);
     if(*out != NULL){
         sprintf(*out, "%s,%s", foovar, baa);
      }
}

and then I call:

int main(void) {
   char * out = NULL;
   foo(&out);
   printf("%s\n", out); /* so far, it works fine */
   free(out); /* the problem. */ 
}

When I call:

free(out);

it given:

*** glibc detected *** ./a.out: free(): invalid next size (fast): 0x09a03050 ***
======= Backtrace: =========
/lib/tls/i686/cmov/libc.so.6(+0x6b161)[0x4ff161]
/lib/tls/i686/cmov/libc.so.6(+0x6c9b8)[0x5009b8]
/lib/tls/i686/cmov/libc.so.6(cfree+0x6d)[0x503a9d]
./a.out[0x804875b]
./a.out[0x804871a]
./a.out[0x80486f9]
/lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe6)[0x4aabd6]
./a.out[0x8048601]
======= Memory map: ========

//do need copy memory map part?

Can someone point out my mistake? I believe that's sprintf() call.. or no, actually, I have no idea. I tried too make a new variable inside function alloc value for it, and then *out = myvariable; and *out = strdup(myvariable) but the free() call give same error.

Update

I see that the problem is inside the function. Any free() call inside it,causes the invalid next size.

for example:

char *f=malloc(2);
strcpy(f,"a");
free(f);

Inside foo() function, gets the above error, on main() function, works normally. I'm completely lost how to fix this.

Upvotes: 1

Views: 1144

Answers (3)

Jack
Jack

Reputation: 16724

The solution:

The problem actually,was on previous malloc().An if() declaration call another function that do too a malloc(),but an if() inside called function,was not working as expected and cosequently storing some invalid values. This caused the heap corruption.

Upvotes: 0

octopusgrabbus
octopusgrabbus

Reputation: 10685

Works for me, but I didn't have computedsize foo, or baa. I agree that you've probably written beyond the end of the memory you allocated.

#include <stdio.h>
#include <stdlib.h>

#define COMPUTEDSIZE 1024
void foo(char ** out) {
     *out = malloc(COMPUTEDSIZE);
     if(*out != NULL){
         sprintf(*out, "%s,%s", "foo", "baa");
      }
}
int main(int argc, char * argv[]) {
   char * out = NULL;
   foo(&out);
   printf("%s\n", out); /* so far, it works fine */
   free(out); /* the problem. */ 
   exit(0);
}

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272457

You have probably written beyond the bounds of the allocated array, thus corrupting the heap (which contains metadata which malloc/free use to manage things).

Tools like Valgrind are designed to help you find this sort of error.

Upvotes: 5

Related Questions