0

My code creates two new nodes in a tree structure below a parent node passed to the function via pointer. Assigning the parent node as the parent of the new nodes works correctly, but the program throws a seg fault when it attempts to assign the new nodes as the left and right children of the parent

//Create new nodes
node* new1 = (node*)malloc(sizeof(node));
new1->parent = par;

node* new2 = (node*)malloc(sizeof(node));
new2->parent = par;

par->left = new1;
par->right = new2;

Here is the struct for reference

typedef struct nd {   
  int data;                               
  struct nd* parent;
  struct nd* left;
  struct nd* right;
}node;
  • 1
    Welcome to Stack Overflow! [dont cast malloc](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Barmar Nov 21 '19 at 21:06
  • 2
    Welcome to Stackoverflow. Don't only describe the problem in words. Show complete code which has the problem. Please see [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) for guidance. For example, in this case `par` is very important but we don't even know what that is as you have not shown its definition nor how it is assigned. – kaylum Nov 21 '19 at 21:07
  • 3
    It sounds like you didn't allocate `par` properly. – Barmar Nov 21 '19 at 21:08
  • Consider using 'calloc' when allocating. It will initialize everything to zero, reducing the risk of random 'junk' data from uninitialized members. – dash-o Nov 21 '19 at 21:10
  • 1
    My guess is that par is either unassigned, or NULL, or passed as the wrong kind of parameter. Are you getting any compile errors? If you are compiling with gcc, add the -Werror -Wall flags and see if that helps. Or give us more context--it's impossible to debug an error with a dereference of par without knowing what par is. (And Barmar is correct--don't cast malloc. Never cast--all it does is hide bugs). (OK, there are a small handful of cases where you need to cast, but you won't run into them for a long time. Until then, never cast). – One Guy Hacking Nov 21 '19 at 21:18

1 Answers1

0

SOLVED: I did not account for the case where the root had not yet been allocated. (I.E the passed pointer is NULL)