0

I am trying to display the second list. when I run the code, the second list gets printed but the compiler throws an exception that says "cur was 0xCDCDCDCD".

I am trying to let the user input a list and then the compiler creates a second list with the square of elements of the first list.

here's the code with the question.


/*
Write a program that inputs from the user a simple linked list of integer elements. The
program should create a new list that is the list of the square of the elements of the
previous list. Output the list.
*/
#include <iostream>
#include <cmath>
using namespace std;

struct node {
    int data;
    node* next;
};

node* input(int n) {
    node* cur, * head, * tmp;
    tmp = new node;
    cout << "enter a new node" << endl;
    cin >> tmp->data;
    head = tmp;
    cur = tmp;
    for (int i = 0; i < n - 1;i++) {
        tmp = new node;
        cout << "enter a new node" << endl;
        cin >> tmp->data;
        cur->next = tmp;
        cur = tmp;
    }
    return head;

}



node* square(node* head, int n) {
    node* head1, * cur, * cur1, * tmp;
    cur= head;
    tmp = new node;
    tmp->data = pow(cur->data, 2);
    head1 = tmp;
    cur1 = tmp;
    cur = cur->next;
    for (int i = 0;i < n - 1;i++) {
        tmp = new node;
        tmp->data = pow(cur->data, 2);
        cur1->next = tmp;
        cur1 = tmp;
        cur = cur->next;
    }
    return head1;
}

void displayList2(node* head1) {
    node* cur;
    cur = head1;
    while (cur != NULL) {
        cout << cur->data << " ";
        cur = cur->next;
    }
}

int main() {
    int n;
    cout << "enter number of nodes: ";
    cin >> n;
    node* head, * head1;
    head = input(n);
    head1 = square(head, n);
    displayList2(head1);
}

is there a problem with the heap memory or something similar? what am I doing wrong?

  • This may help: https://stackoverflow.com/questions/8275418/with-c-i-get-pointer-with-0xcdcdcdcd-when-creating-a-class-what-is-happenin – Werner Henze Jan 29 '21 at 16:53
  • You should always initialize the next pointer when creating a new node. – drescherjm Jan 29 '21 at 17:57
  • 1
    General note: Whenever you see a number that's highly repetitious or spells out a recognizable word of phrase, the program is probably trying to tell you something. Look the number up in a [list of common debugging codes](https://en.wikipedia.org/wiki/Magic_number_(programming)#Debug_values) – user4581301 Jan 29 '21 at 20:21
  • Initialize your variables: `struct node { int data = 0; node* next = nullptr; };` – Eljay Jan 29 '21 at 20:43

0 Answers0