CodexBloom - Programming Q&A Platform

Segmentation fault when accessing struct member through pointer in C

👀 Views: 82 💬 Answers: 1 📅 Created: 2025-06-01
c pointers segmentation-fault C

Can someone help me understand After trying multiple solutions online, I still can't figure this out. I'm encountering a segmentation fault when trying to access a member of a struct through a pointer. I've defined a struct `Person` and created a function to initialize and print its details. However, when I call the function to print the details of a `Person` instance, I get a segmentation fault. Here's the relevant code snippet: ```c #include <stdio.h> #include <stdlib.h> typedef struct { char name[50]; int age; } Person; void initializePerson(Person *p, const char *name, int age) { strcpy(p->name, name); p->age = age; } void printPerson(const Person *p) { printf("Name: %s, Age: %d\n", p->name, p->age); } int main() { Person *p1 = malloc(sizeof(Person)); initializePerson(p1, "Alice", 30); printPerson(p1); free(p1); return 0; } ``` When I run this code, it works fine, but if I change the initialization of `p1` to: ```c Person *p1; initializePerson(p1, "Alice", 30); ``` I get a segmentation fault when trying to access `p1->name`. I thought that declaring `p1` without allocating memory would still allow me to pass it to `initializePerson`, but it seems like I'm missing something crucial here. I’ve also checked that the function is receiving the pointer correctly. Am I misunderstanding how pointers work in this context? How can I avoid this segmentation fault in my code? This issue appeared after updating to C 3.11. What am I doing wrong?