The structure of Node is the following:
struct Node {
int data;
Node *next;
bool someBool;
};
I have the following couple of lines:
Node *hello = new Node{data, cur, !new_head}; // line A
array[new_head_index] = hello; // line B
} // line C
Value of new_head_index
is confirmed to be 1 by GDB on all 3 lines.
GDB confirms, on lines A, B, and C, when I do p *hello
(print the contents of hello
), I get:
(gdb) p *hello
$7 = {data = 888, next = 0x8414e70, someBool = false}
But printing the contents of array@2
(array has length 2, declared in main as Node *heads[numHeads] = {new Node{0, nullptr, false}, nullptr};
) has this on lines B and C (before line is actually executed):
(gdb) p **array@2
$8 = {{data = 777, next = 0x8414e70, someBool = true}, {data = 33, next = 0x378, someBool = 112}}
(The 777 node is expected, I filled it in before).
While on line A, it has:
(gdb) p **array@2
$9 = {{data = 777, next = 0x8414e70, someBool = true}, {data = 61265, next = 0x0, someBool = false}}
Essentially, hello
is not being assigned to array[1]
. What could be a possible reason for this?
Here is a minimal reproducible example: main.cc
#include <iostream>
#include <string>
#include "new_mod.h"
using namespace std;
int len(Node **array) {
int i = 0, count = 0;
while (array[i++]) { ++count; }
return count;
}
void attach(Node **array, int head, int index, int data) {
Node *hello = new Node{data, cur};
array[new_head_index] = hello;
}
int main() {
string command;
int head;
Node *array[numHeads] = {new Node{0, nullptr}, nullptr};
while (cin >> command) {
if (command == "a") {
int m, x;
cin >> head >> m >> x;
attach(array, head, m, x);
}
}
}
mod.h
#ifndef MOD_H
#define MOD_H
#include <ostream>
struct Node {
int data;
Node *next;
bool someBool = false;
};
const int numHeads = 2;
void attach(Node **array, int head, int index, int data);
#endif
Try putting in this input (I've named this file a.in
)
a 0 0 777
a 0 1 888
Compile with g++ -Wall -g main.cc -o newe
so you can do things with gdb!
By the way, here's what I did in gdb to get the above problem:
gdb newe
b attach(Node**, int, int, int)
run <a.in
layout n
c
n
n
n
n
n
n
n (comment: I did n until line Node *hello = new Node{data, cur};)
p **array@2
n
n
p **array@2 (the problem is shown)