I’m new to C so please correct anything in this question, and also I might be too vague in my question as well. I have code that kind of goes like this, and I’m getting a segmentation fault. I read online that segmentation faults happen usually when u access a pointer that points to nothing
struct apple get(char* name) {
struct apple a;
a.name = name;
return a;
}
struct apple* read(){
struct apple* ap = (struct apple*)malloc(2*sizeof(struct apple));
ap[0] = get("bob");
return ap;
}
// loop through in another function which reads a pointer to an
// apple object in the array and then accesses apple->name
when it accesses apple->name there is a segmentation fault. I am assuming this is because the apple object was declared as a local variable and its freed later by c??? I really have no idea why I get a segmentation fault or how to fix it or how c works with freeing structs that were initialized as a local variable in a function. Can someone please tell me what’s going on, thanks!
Well, segmentation fault errors happen when the pointer points to something wrong, not necessarily when the pointer is empty.
There is nothing wrong in the code snippet that you posted:
"bob"is achar*that stays valid for the life of the program, and the return ofappleis done by value, so you are not returning a pointer to a local either. The issue is most likely in the code that iterates over apples returned fromread().