Hi folks,

I am learning C++ programming.
Below mentioned program giving segmentation fault ONLY WHEN if I declare 'struct s a;'
ABOVE 'struct s *b;'.
Can anybody tell me the reason?

#include<iostream>
using namespace std;

struct s
{
 int m;
};

int main()
{
 struct s a; // if I put this below 'struct s *b; then i wont get segmentation fault
 struct s *b;
 b->m = 5;
 cout<<"m="<<b->m<<endl;

return 0;
}

output:
./a.out
Segmentation fault

Dani AI

Generated

Short answer: the crash comes from dereferencing an uninitialized automatic pointer. Dereferencing a pointer that never got a valid address is undefined behavior, so the program can crash or—by coincidence—appear to work. As noted the pointer needs to be given a valid target; observed that moving the a declaration changed the symptom — that’s just stack-layout luck. called it “pure luck,” which is accurate, and is right about simplifying struct usage in C++.

Why the declaration order changes things: local variables are typically placed on the stack and hold whatever bits were there before. An uninitialized pointer contains an indeterminate bit pattern; changing the order of declarations changes offsets and the surrounding stack contents, so the pointer’s initial value changes. Sometimes that value happens to be a safe address and the code “works”; other times it points to inaccessible memory and you get a segfault. The important point is this is undefined behavior and cannot be relied on.

Safe fixes (pick one): avoid naked, uninitialized pointers; always initialize. Use a stack object, allocate and own the object, or use a smart pointer. Example using modern C++:

#include <memory>

struct Data { int m; };

int main() {
    auto p = std::make_unique<Data>(); // p is valid
    p->m = 5;
}

Debugging tips: compile with warnings (-Wall -Wextra) and run under sanitizers (-fsanitize=address,undefined -g) or Valgrind to catch use-of-uninitialized-memory. Initialize pointers to nullptr if you must declare them first, check before dereferencing, or prefer automatic objects/std::unique_ptr. Treat any non-deterministic success as a bug to fix, not as correct behavior.

Recommended Answers

All 4 Replies

you forgot to make pointer b point to anything. struct s* b = &a;

Thanks Ancient Dragon, But if i remove or move struct s a; then code will work :-O:-/

eg:

#include<iostream>
using namespace std;
 
struct s
{
 int m;
};
 
int main()
{
 //struct s a;[B] moving this below to struct s *b; NO segfault [/B]
 struct s *b;
 struct s a;


 b->m = 5;
 cout<<"m="<<b->m<<endl;
 
return 0;
}

It's pure luck. What you are doing is illegal. It can work or it cannot.

As an aside, this is C++; you don't need to keep repeating "struct" every time you create a new instance of one.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.