简体   繁体   中英

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;
}

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM