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


i think i've got down 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 this:

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

if can shed light on understanding failing, it'd appreciated.

you pass pointer value, not reference, whatever arr inside foo not make difference outside foo-function. m_pgladiator wrote 1 way declare reference pointer (only possible in c++ btw. c not know references):

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; } 

another (better imho) way not pass pointer argument return pointer:

int main(int argc, char ** argv) {   int * arr;    arr = foo();   printf("car[3]=%d\n",arr[3]);   free (arr);   return 1; }  int * foo(void ) {   int * arr;   arr = (int*) malloc( sizeof(int)*25 );   arr[3] = 69;   return arr; } 

and can pass pointer pointer. that's c way pass reference. complicates syntax bit - that's how c is...

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; } 

Comments