C free(): invalid pointer allocated in other function

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

    Arguments in C are always passed by value. So, when you call alloc(pointer), you just pass in whatever garbage value pointer contains. Inside the function, the assignment p = (int*)... only modifies the local variable/argument p. Instead, you need to pass the address of pointer into alloc, like so:

    int alloc(int **p) {
        *p = malloc(sizeof(int)); // side note - notice the lack of a cast
        ...
        **p = 4; // <---- notice the double indirection here
        printf("%d\n", **p); // <---- same here
        return 1;
    }
    

    In main, you would call alloc like this:

    if (!(alloc(&pointer))) {
        ....
    

    Then, your code will work.

提交回复
热议问题