0

This is in my main.c

int main(){

int size = 5;
Path Solution;
PathInit(&Solution,size);
printf("Size: %d\n",Solution.size);
printf("top: %d", Solution.top);
}

This is in my path.h

typedef struct{
int size;
int top;
int *item;
}Path;

This is in my path.c

void PathInit(Path *P, int vsize){
P = (Path *)malloc(sizeof(Path));
P->size = vsize;
P->item = (int *)malloc(sizeof(int)*vsize);
P->top = -1;

}

The expected output is

Size: 5
top: -1

However the output is something along the lines of

Size: 3412832
top: 0

Can someone explain why my struct is not initializing properly. Also this isn't my full code but ive narrowed the problem down to these sections. Any help would be great. Thanks

0

2 Answers 2

5

You are using the stack:

Path Solution;

and passing a pointer:

PathInit(&Solution,size);

so you don't need to reserve space with malloc:

void PathInit(Path *P, int vsize){
    P = (Path *)malloc(sizeof(Path)); /* Remove this line */
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks alot, this really helped :D
2

As mentioned in the answer of @Alter Mann's, the issue is that you mess up with the stack storage, which is undefined behaviour. In case you want to use dynamic allocation, you need to pass a pointer to pointer (and btw there is no need to cast the result of malloc in C), so you can modify it in your function, like:

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

typedef struct {
    int size;
    int top;
    int *item;
} Path;

void PathInit(Path **P, int vsize) { // pass pointer to pointer so we can modify it
    *P = malloc(sizeof(Path)); // No need (and not recommended) to cast malloc in C
    (*P)->size = vsize;
    (*P)->item = malloc(sizeof(int) * vsize);
    (*P)->top = -1;
}

int main() {

    int size = 5;
    Path* Solution; // this is now a pointer
    PathInit(&Solution, size);
    printf("Size: %d\n", Solution->size);
    printf("top: %d", Solution->top);
    free(Solution->item);
    free(Solution);
}

Otherwise you need to return the pointer from your function:

Path* PathInit(int vsize) {
    Path* tmp = malloc(sizeof(Path));
    tmp->size = vsize;
    tmp->item = malloc(sizeof(int) * vsize);
    tmp->top = -1;
    return tmp;
}

and call it like

Path* Solution;
Solution = PathInit(size);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.