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

前端 未结 5 697
囚心锁ツ
囚心锁ツ 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:31

    You pass the pointer by value, not by reference, so whatever you do with arr inside foo will not make a difference outside the foo-function. As m_pGladiator wrote one way is to declare a reference to pointer like this (only possible in C++ btw. C does not know about 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 is to not pass the pointer as an argument but to return a 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 you can pass a pointer to a pointer. That's the C way to pass by reference. Complicates the syntax a bit but well - 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;
    }
    

提交回复
热议问题