C free(): invalid pointer allocated in other function

后端 未结 5 1897
醉梦人生
醉梦人生 2020-12-07 06:37

I\'m new in StackOverflow. I\'m learning C pointer now.

This is my code:

#include 
#include 

int alloc(int* p){
    p         


        
5条回答
  •  心在旅途
    2020-12-07 07:00

    You are passing the pointer by value into your alloc function. Although that function takes a pointer to an int, that pointer itself cannot be modified by the function. If you make alloc accept **p, set *p = ..., and pass in &pointer from main, it should work.

    #include 
    #include 
    int alloc(int** p){
      *p = (int*) malloc (sizeof(int)); 
      if(!*p){
        puts("fail\n"); 
        return 0; 
      } 
      **p = 4; 
      printf("%d\n",**p);
      return 1; 
    } 
    int main() { 
      int* pointer; 
      if(!alloc(&pointer)){ 
        return -1;
      } else { 
        printf("%d\n",*pointer);
      } 
      free(pointer);
      return 0;
    }
    

提交回复
热议问题