0

How can I change a heap allocated global pointer from within a function? Here is what I am working with, (call to modify_p seg faults and I can't see much in the debugger):

#include <stdio.h>
#include <stdlib.h>

int *p;

void set_p(int *p, int sz) {
        p = malloc(sz * sizeof(int));
}

void modify_p(int *p) {
    p[0] = 2;
}

int main(int argc, char *argv[])
{
    set_p(p, 3);
    modify_p(p);
    //printf("%d\n", p[0]);
    // should print 2   
    return 0;
}

Thanks

jackw11111
  • 1,457
  • 1
  • 17
  • 34
  • This is a duplicate of this question: https://stackoverflow.com/questions/1398307/how-can-i-allocate-memory-and-return-it-via-a-pointer-parameter-to-the-calling – jackw11111 Jun 06 '19 at 06:26

2 Answers2

3

The issue is that you pass a copy of p to set_p. So the original p is never modified and never points to valid memory, and the copy is lost at the end of set_p, leaking the memory. Instead, pass a pointer to p (so a pointer to a pointer), like this:

void set_p(int **p, int sz) {
    *p = malloc(sz * sizeof(int));
}

And call the function like this:

set_p(&p, 3);

Then you get the expected result.

Blaze
  • 16,736
  • 2
  • 25
  • 44
1

One way would be to do this:

#include <stdio.h>
#include <stdlib.h>

int *p;

void set_p(int sz) {
        p = malloc(sz * sizeof(int));
}

void modify_p() {
    p[0] = 2;
}

int main(int argc, char *argv[])
{
    set_p(3);
    modify_p();
    printf("%d\n", p[0]);
    // should print 2   
    return 0;
}

As p is declared outside of any function, you can write directly to it. When you do set_p(p, 3);, the set_p function will have it's local copy of the variable.

If you want to change what a pointer points to, you have to pass the address of the pointer (as shown by Blaze).

babon
  • 3,615
  • 2
  • 20
  • 20
  • `modify_p(p); --> modify_p();` – MayurK Jun 04 '19 at 07:04
  • @MayurK Strictly speaking, invoking `modify_p(p)` also works because the function actually takes an unspecified number of args. Anyways, modified to keep things simple. – babon Jun 04 '19 at 07:07
  • Thank you, I am sorry I didn't mention that `modify_p` should really have been `modify(int *p, int sz)` because it needs to work for more than one pointer. – jackw11111 Jun 04 '19 at 07:11