Alex Rivera | Logout

Malloc inside a function call appears to be getting freed on return?

Asked 2008-09-19T20:44:51.413
16

I think I've got it down to the most basic case:

int main(int argc, char ** argv) {
  int * arr;

  foo(arr);
  printf("car[3]=%d\n",arr[3]);
  free (arr);
  return 1;
}

void foo(int * arr) {
  arr = (int*) malloc( sizeof(int)*25 );
  arr[3] = 69;
}

The output is this:

> ./a.out 
 car[3]=-1869558540
 a.out(4100) malloc: *** error for object 0x8fe01037: Non-aligned pointer
                         being freed
 *** set a breakpoint in malloc_error_break to debug
>

If anyone can shed light on where my understanding is failing, it'd be greatly appreciated.

Edit
Report

1 Answer

0

You cannot change the value of your argument (arr) if it's not passed in by reference (&). In general, you would want to return the pointer, so your method should be:

arr=foo();

It's bad juju to try to reassign arguments; I don't recommend the (&) solution.

answered 2008-09-19T20:50:26.080

Your Answer