Reputation: 257
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
.
Upvotes: 0
Views: 603
Reputation: 1
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.
Upvotes: 3
Reputation: 731
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.
Upvotes: 1
Reputation: 9648
One solution is to pass a pointer to the pointer:
int main()
{
deque *d;
initDeque( &d );
}
void initDeque( deque **d )
{
*d = malloc( sizeof( deque ) );
}
Upvotes: 3