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

前端 未结 5 704
囚心锁ツ
囚心锁ツ 2020-12-07 16:05

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         


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-07 16:33

    You've allocated arr in foo, but that pointers value is stored in the call stack. If you want to do this, do it like this:

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

    And in main, simply pass a pointer to foo (like foo(&arr))

提交回复
热议问题