0

Hey I'm trying to move pointer memory allocation d =(deque*)malloc(sizeof(deque)); into first function called void initDeque(). I tried leaving declaration in main and allocating memory in the function, but program just crashes after initializing the deque and I can't use the pointer in other functions.

Here's the code:

int main(){
    int x;
    deque *d;
    d = (deque*)malloc(sizeof(deque));

    initDeque(d);
    putFront(d,10);

And the function where I want to move memory allocation for pointer:

void initDeque(deque *d){ //Create new deque
    //d = (deque*)malloc(sizeof(deque));
    printf("Initializing deque\n");
    d->front=NULL;
    d->rear=NULL;
}

Program runs great if declaration and allocation is in the main(), but it crashes when I put allocation into void initDeque.

  • 2
    [Thou shalt not cast the result of malloc in C, else there will be much wailing and gnashing of teeth.](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Paul R Mar 17 '15 at 17:06

3 Answers3

3

One solution is to pass a pointer to the pointer:

int main()
{
    deque *d;
    initDeque( &d );
}

void initDeque( deque **d )
{
    *d = malloc( sizeof( deque ) );
}
clcto
  • 9,530
  • 20
  • 42
3

Arguments (even pointers) are passed by value in C.

So return the pointer:

deque *make_queue(){ //Create new deque
  deque *d = malloc(sizeof(deque));
  if (!d) { perror("malloc"); exit(EXIT_FAILURE); };
  printf("Initializing deque\n");
  d->front=NULL;
  d->rear=NULL;
  return d;
}

and call d = make_queue(); in start of your your main; when doing a malloc always test for failure.

Alternatively, pass the address of a pointer, as answered by clcto

Read wikipage on C dynamic memory management. Don't forget to call free appropriately. For debugging, use valgrind if available. Avoid memory leaks (and double free-s). When you are more mature in C, read the wikipage on garbage collection, perhaps consider using in some cases Boehm conservative garbage collector.

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
1

When calling the function you are sending the values in the d variable as argument to the function instead of its pointer (aka memory address).

initDeque(d);

In order to send the pointer itself you must send its memory address instead:

initDeque(&d);

For this I would also advise you to use a pointer of a pointer, this way you can send the address you are pretending to allocate the data even if you haven't used memalloc already.

The value of &d will be a memory address if you try to display it so make sure you remember its a pointer of a pointer later.

José Algarra
  • 651
  • 1
  • 6
  • 10