0

I am using Visual Studio 2013. I am getting the Access violation reading location 0xCDCDCDD1 error. References from Wikipedia: Magic Numbers, here, and this question tell me that I am using an uninitialized pointer. I think the problem is with the malloc function I'm using, although I did refer to the CPlusPlus doc before using it.

My code:

#include "SingleNode.h"
#include "SingleList.h"
#include <iostream>
SingleList::SingleList() {}
SingleList::~SingleList() {}
...
    void SingleList::addHead(int value){
    ISingleNode *temp1 = (ISingleNode *)malloc(sizeof(SingleList));
    head = NULL;
    temp1->setValue(value);
    temp1->setNext(head->getNext());
    if (!head->getNext())
    {
        head = temp1;
    }
    else
    {
        temp1->setNext(head->getNext());
        head = temp1;
    }
}

    ...

The error is in the line temp1->setValue(value);

The setValue(int value) function is included from here:

#include "SingleNode.h"
SingleNode::SingleNode() {}
SingleNode::~SingleNode() {}
void SingleNode::setValue(int value){
    this->value = value;
}
int SingleNode::getValue(){
    return value;
}
ISingleNode * SingleNode::getNext(){
    return next;
}
void SingleNode::setNext(ISingleNode * next){
    this->next = next;
}

SingleNode.h:

#pragma once
#include "Interfaces01.h"
class SingleNode :public ISingleNode{
private:
    int value;
    ISingleNode * next = NULL;
public:
    SingleNode();
    ~SingleNode();
    void setValue(int value);
    int getValue();
    ISingleNode * getNext();
    void setNext(ISingleNode * next);
};

SingleList.h:

#pragma once
#include "Interfaces01.h"
class SingleList :public ISingleList{
private:
    int value;
    ISingleNode * head=NULL;
    ISingleNode * temp=NULL;
    ISingleNode * next=NULL;
    ISingleNode * temp1;
public:
    SingleList();
    ~SingleList();
    ISingleNode * getHead();
    void setHead(ISingleNode * head);
    void addHead(int value);
    void orderSort2();
    void orderSort3();
    void sequenceOrderSort();
    void reverse();
    ISingleNode * swap(ISingleNode * head, int k);
    ISingleNode * get_node(ISingleNode * head, int k);
};

On breaking at the line, the debugger is showing me the following values:

Visual Studio 2013 debug values at breakpoint

trincot
  • 317,000
  • 35
  • 244
  • 286
Ayush Khemka
  • 47
  • 1
  • 9

1 Answers1

5
  1. Change:

    ISingleNode *temp1 = (ISingleNode *)malloc(sizeof(SingleList));
    

    into:

    ISingleNode *temp1 = new SingleList;
    
  2. You are accessing a NULL pointer:

    head = NULL; // set to NULL
    temp1->setValue(value);
    temp1->setNext(head->getNext()); // oops!
    

    you probably meant:

    void SingleList::addHead(int value)
    {
        ISingleNode *temp1 = new SingleList;
        temp1->setValue(value);
        temp1->setNext(head);
        head = temp1;
    }
    
Piotr Skotnicki
  • 46,953
  • 7
  • 118
  • 160