This code is giving me runtime error. Here, first I want to take a integer input which determine the number (n) of nodes in the graph. Then for n-1 time I want take two integer input which will give the adjacency information.

#include <set>
#include <map>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <cctype>
#include <cstdio>
#include <string>
#include <vector>
#include <cassert>
#include <cstdlib>
#include <cstring>
#include <sstream>
#include <iostream>
#include <algorithm>

#define MAXEDGE 1000


using namespace std;


typedef struct{
    int linked_to;
}edg;

typedef struct{
    edg edge[MAXEDGE];
    bool visited[MAXEDGE];
    int total_nodes;
}graph;
	
int main() {
    
        int u,v,n = 0;
        graph *g;
        
        scanf("%d",&g->total_nodes);
       
        for(int i = 0; i<g->total_nodes; i++){
                scanf("%d %d",&u,&v);
                g->edge[u].linked_to = v;
        }        
    
    return 0;
}

Dani AI

Generated

Root cause: the pointer g is never given valid storage before any g->... access, so the program invokes undefined behavior and crashes. As and observed, the pointer must point at a real object (stack or heap) or a different design should be used; correctly contrasts -> and .. Beyond allocation, the posted design has other risks: fixed-size arrays (MAXEDGE) can be mismatched to the actual node/edge counts, index origin (0 vs 1) can produce out-of-bounds access, and looping n times when the intent was n-1 (only valid for a tree) is a logic/contract issue.

A safer, clearer approach is to use STL containers that size themselves and avoid raw pointer management. Example (1-based node numbering, undirected tree with n-1 edges):

#include <iostream>
#include <vector>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n;
    if (!(cin >> n)) return 0;
    vector<vector<int>> adj(n + 1);           // use n if nodes are 0..n-1
    for (int i = 0; i < n - 1; ++i) {
        int u, v;
        cin >> u >> v;
        if (u < 1 || u > n || v < 1 || v > n) continue; // validate input
        adj[u].push_back(v);
        adj[v].push_back(u); // omit for directed graph
    }
    vector<char> visited(n + 1, 0);
    // graph algorithms follow...
}

Troubleshooting checklist: verify the actual number of edges (trees use n-1; general graphs do not), always validate u/v ranges before indexing arrays, initialize any boolean/visited buffers, and prefer container-based storage or smart pointers if dynamic allocation is required. To catch memory errors quickly, build with sanitizers (AddressSanitizer) or run under Valgrind; these tools point to the exact invalid access rather than guessing the cause.

Recommended Answers

All 6 Replies

Where did you allocate the memory

Where did you allocate the memory

Sorry, I don't understand your question. Why I allocate memory here?

g is pointer to an object of type graph,
you have to create the object, by either malloc or new
and then point g to the address

graph *g; creates a pointer (to memory) but you fail to provide any memory to point to. You can do one of three things:

  • Create an object instead of a pointer ( graph g; )
  • Create an object and assign the pointer to that objects address ( graph g, *gp = &g; )
  • Allocate the memory yourself ( graph * g = new graph; )

graph *g; creates a pointer (to memory) but you fail to provide any memory to point to. You can do one of three things:

  • Create an object instead of a pointer ( graph g; )
  • Create an object and assign the pointer to that objects address ( graph g, *gp = &g; )
  • Allocate the memory yourself ( graph * g = new graph; )

Thank You. 2nd one is working for me. But what about 1st one? How can I assign value for the object(g) using 1st option?

Would you plz make me clear about how 2nd one is working? Is it like this...
For example, pointer gp is first pointing the object g which is a graph type object. then the value of total_nodes is assigned through the pointer to the object.

When you have syntax like g->total_nodes it means that you access the object pointed to by "g" and then access its data member called total_nodes .

When you write it as g.total_nodes it means that you access the data member called total_nodes that belongs to the object "g".

So, if you want the first version to work, i.e. the version with Graph g; , then you have to replace all the g-> with g. , because now, "g" is an object, and not a pointer to an object (like in your original code).

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.