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

Exception thrown: Write access violation C++

I want to fill (obj * m) with numbers 2 4 6 8 10 12 14 16 18 20. In Microsoft Visual Studio Professional 2019 I am getting this error: "Exception thrown: Write access violation" at the line "n-> val = data;" or line 15. But then I went into the DEV C ++ application and there I realized what the error was, for some reason the repetition started and the array generally deteriorated, roughly speaking, not counting the initial element. By running the program, you will see everything for yourself, I brought it up there and everything is clearly visible.

#include <iostream>
using namespace std;
class obj{
public:
    int val, k;
    obj* next;
    obj* n;
    int current = 0;
    
    void func(int data){
        for(n = this, k=0; k<current; n = n->next,k++){
            cout<<"k= "<<k<<" = "<<n<<" = "<<n->val<<" curr= "<< current<<", ";
        }
        cout<<endl;
        n->val = data;
        current++;
    }
    
    void print(){
        for(n =this, k = 0; k<10;n = n->next,k++)
        {
            cout<<n->val<<"  ";     
        }
        
    }
};

int main() {
    obj *m;
    m=new obj [100];
    for(int i=2; i<=20;i+=2)
    {
        m->func(i);
    }
    m->print();
    delete[] m;
    cout << endl;
    return 0;
}

>Solution :

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

In your code, next is not initialized, so n becomes to point wrong address during iteration in func

int main() {
    obj *m;
    m = new obj[100];

    /* Initialize `next` */
    for (int i = 1; i < 100; i++)
    {
        m[i - 1].next = &m[i];
    }

    for (int i = 2; i <= 20; i+= 2)
    {
        m->func(i);
    }
    m->print();delete[] m;
    cout << endl;
    return 0;
}
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