简体   繁体   中英

Segmentation Fault while malloc and sizeof

Sorry if I'm offending anyone but I started learning C this week and I got a segmentation fault while compiling this. Can I please have a second pair of eyes to help me with this error?

void Space(void *empty, size_p s)
{
    empty = malloc(s);
}

int main()
{
    int *p = NULL;
    Space(p, sizeof(p));
    *p = 7;

    return;
}

empty is just a pointer variable - it contains "some" address, but it is still a local variable in the context of Space . If you want to update the value of int *p in Space , you'll need to pass a pointer to it:


int main()
{
    int *p = NULL;
    Space(&p, sizeof *p);
    *p = 7;

    return;
}

void Space(void **empty, size_p s)
{
    *empty = malloc(s);
}

Also, you have a bug where you call Space : Space(p, sizeof(p));

sizeof(p) is the size of the int * variable but you want to allocate the size of an int as that's what you're storing in p . So that line should instead be: Space(&p, sizeof *p);

void * Space(void *empty, size_t s)
{
    empty = malloc(s);
    return empty;
}

int main()
{
    int *p = NULL;
    p = Space(p, sizeof(int));
    *p = 7;

    return 0;
}

You can change the Space function to return a void * or an int * . The variable empty is a copy of the pointer in main . When you change the value in Space , because it is a copy, the change never makes it back to main .

I changed sizeof(p) to sizeof(int) . This is more of personal preference but I try to only give types as the argument to sizeof . You can get surprising results when you apply sizeof to variables.

I really like @DIMMSum's answer but I know pointer-to-a-pointer can be confusing especially when starting out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM