Staas
Staas

Reputation: 3

How to fix the error: Exception thrown : read access violation?

Im trying to send DATA from my arduino to my visual studio c++ program. But after my program on visual studio recives the data it crashes and I get the error code:

"Exception thrown: read access violation. _Ptr_user was 0x7."

Can you guys help me?

I have the following code:

while (video.read(frame))
    {
        cv::imshow("videofeed", frame);
        cv::Mat frame2;

        std::string test;
        char* sensor = const_cast<char*>(test.c_str()); 
        arduino.readSerialPort(sensor, MAX_DATA_LENGTH);

        int b = *sensor;

        if (b > 0) {
            cout << b;
            Sleep(1000);
        }

        if (waitKey(30) == 'c') {
            break; 
        }
    }
}

Upvotes: 0

Views: 2841

Answers (1)

molbdnilo
molbdnilo

Reputation: 66371

You need some space to write into – you have none – and writing through a pointer acquired from c_str() has undefined behaviour.

test is an empty string, but you apparently want it to have MAX_DATA_LENGTH characters.

std::string test(MAX_DATA_LENGTH, '\0');

You also should not use const_cast<char*>(test.c_str()).

Use either

char* sensor = &test[0];

or

char* sensor = test.data();

You could also use std::vector<uint8_t>, since it looks like you're sending arbitrary data rather than strings.

std::vector<uint8_t> test(MAX_DATA_LENGTH);
arduino.readSerialPort(test.data(), MAX_DATA_LENGTH);
int b = test[0];

Upvotes: 2

Related Questions