C free(): invalid pointer allocated in other function

后端 未结 5 1891
醉梦人生
醉梦人生 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:08

    Everything in C is pass-by-value. This means that functions always operate on their own local copy of what you pass in to the function. Usually pointers are a good way to mimic a pass-by-reference scheme because a pointer and a copy of that pointer both contain the same memory address. In other words, a pointer and its copy both point to the same space.

    In your code the issue is that the function alloc gets its own local copy of the pointer you're passing in. So when you do p = (int*) malloc (sizeof(int)); you're changing the value of p to be a new memory address, but the value of pointer in main remains unchanged.

    You can get around this by passing a pointer-to-a-pointer, or by returning the new value of p.

提交回复
热议问题