Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Problems with pointers and struct (C++)

Can someone tell me what is wrong with the following code?

#include <iostream>
using namespace std;

typedef struct point{
  int key;
  struct point * key0;
} pnt;

int main() {
  pnt * p = new pnt;
  p->key = 1;
  p->key0->key = 2;
}

I’m kinda new to C++ and I’m still trying to understand these concepts.

I was expecting to be able to set some arbitrary value to the structure I defined. I was just experimenting if I understood how that work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The compiler just says I used an illegal instruction.

>Solution :

This line:

pnt * p = new pnt;

Allocates a pnt struct, but does not initialize it. The address of the allocated struct is assigned to p.

In this line:

p->key = 1;

You initialize the key field.

But at the point the key0 field is still uninitialized.
But in this last line:

p->key0->key = 2;

You attempt to dereference the uninitialized key0 (with key0->key).
This is causing undefined behavior.

To avoid it you need to initialize key0 either by allocating another pnt struct and using its address, or by using the address of an existing pnt object.

Side notes:

  1. In C++ it is usually better to avoid using raw new.
    To begin with, it requires a delete (without it you get a memory leak – as in your code).
    Also there are better alternatives like using smart pointers.

  2. It is better to avoid using namespace std;. See here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading