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.
The compiler just says I used an illegal instruction.
This line:
pnt * p = new pnt;
Allocates a pnt
struct, but does not initialize its contents. The address of the allocated struct is assigned to p
.
In this line:
p->key = 1;
You initialize the key
field.
But at this point, the key0
field is still uninitialized.
But, in this last line:
p->key0->key = 2;
You attempt to dereference the uninitialized key0
field (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:
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, or in other cases - using standard containers.
It is better to avoid using namespace std;
. See here.
In C++, there's no need for typedef
to create your struct type (it's common in C). You can simply use:
struct pnt{
...
pnt * key0;
};