Simple structure

Hello. I'm trying to write abstract data type - List. But first I have to understand some properties of structures. I wrote this code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
struct Example {
  int value;
};

int main(){
  Example * Test1;
  Test1->value = 5;
  
  Example * Temp = new Example;
  Temp = Test1;
  
  cout << "Value for Test1 = " << Test1->value << " Value for Temp:" << Temp->value << endl;

  Temp->value = 10;
  
  cout << "Value for Test1 = " << Test1->value << " Value for Temp." << Temp->value <<endl;
  //delete Temp;
  
   cout << "Value for Test1 = " << Test1->value<<  endl;
}
  

Output is really nothing new for me but this time i can't repair this.
memory protection violation (core dumped)
The main purpose of this program is to show me what would happend when i create two objects and sign firt one to second one and then change one of them or even remove it what impact will this have to another. Sorry if my English is not good enough to understand my idea.
Consider this code from your program

Example * Test1;
Test1->value = 5;

You declared pointer Test1 that has no initial value. Also you did not allocated memory for an object of type Example to which the pointer could refer to. So the second statement is invalid. You are trying to assign 5 to unknown address for what you have no access.

The valid code could look the following way

Example * Test1 = new Example();
Test1->value = 5;

EDIT: Also this code snip leads to a memory leak

Example * Temp = new Example;
Temp = Test1;

You allocated a memory and stored its address in Temp and then you overwrote this variable. So the allocated address is lost.
Last edited on
Unless there's a reason for using dynamic memory allocation, the object could just be created on the stack:

1
2
Example test;
test.value = 5;


This example is typically more efficient and less error-prone (to resource leaks).
It was not my intention to create dynamic object. Thank you very much. I figured that out and unfortunatly it is not working as i wanted to. I want to find element with value of X on the list and then remove it. I realize some other property of lists. Anyway this problem is solved.
Last edited on
Topic archived. No new replies allowed.