0

I have a pointer to a Tasks struct which has three fields, tid,difficulty & next. I want to compare the difficulty of the next task from a task with a number but i'm getting the attached error when i try what you're seeing below:

struct Tasks
{
    int tid;                      /*Task's identifier*/
    int difficulty;               /*Task's difficulty*/
    struct Tasks *next;           /*Pointer to the next node*/  
};

struct Tasks* curr = (*player)->tasks_head->next;
if(curr->next->difficulty < difficulty) {...}

Here's how i'm allowcating memory for a new node:

struct Tasks* node = (struct Tasks*) malloc(sizeof(struct Tasks)); // could return null if not enough mem
    
if(node == NULL) return 0;
// add data to the new node
node->tid = tid;
node->difficulty = difficulty;
node->next = NULL;

Exception thrown: read access violation. curr->next was 0xCDCDCDCD

I thought i can dereference the next pointer by doing *(curr->next)->difficulty but that doesn't allow me to compile and i don't understand why.

Stelios Papamichail
  • 955
  • 2
  • 19
  • 57
  • 3
    0xCDCDCDCD is the bitpattern Visual studio uses when [memory is allocated on the heap but not initialized](https://stackoverflow.com/questions/127386/in-visual-studio-c-what-are-the-memory-allocation-representations) So show us how you construct new nodes. – Botje Nov 04 '20 at 09:47
  • @Botje, thank you, just added it – Stelios Papamichail Nov 04 '20 at 09:52
  • 2
    Please don't use malloc in C++ code. Use `new Tasks` instead. What do you do with `node` afterward? How is `(*player)->tasks_head` filled in eventually? – Botje Nov 04 '20 at 09:53
  • @Botje sorry about that, sometimes i get confused between C & C++. I changed it everywhere but the code still persists which according to the post means that i haven't initialized the memory allocated for curr->next. I tried exiting the if statement by also doing `curr->next != NULL)`. Wouldn't that be triggered if the memory for curr->next hasn't been initialized? – Stelios Papamichail Nov 04 '20 at 10:01
  • 2
    "uninitialized" does not necessarily mean "equal to NULL" or "not equal to NULL". You should figure out where you're creating Tasks objects that don't have their `next` field filled in. – Botje Nov 04 '20 at 10:03
  • @Botje you were absolutely right, i missed some task's next fields. Thank you. Could you post an answer for me to accept? – Stelios Papamichail Nov 04 '20 at 10:17
  • This reads more like C code than like C++ code – Sebastian Hoffmann Nov 04 '20 at 10:18

0 Answers0