C++ How do I prevent Memory Protection Violation?

I have a problem with memory violation problem that occurs if reach else if(argc == 2)

I’m trying to have a nice written script with no errors like that, anything else works like a charm…

Here’s a code fragment:

//...
// POWER ON
        if(strcmp(argv[2], "on") == 0)
        {
            // GPIO On
            pin_on();
            // Open the serial port READ-WRITE
            int serial_port = open("/dev/ttyS5", O_RDWR);
            // Load serial port settings
            settings(serial_port);
            // POWER ON Message
            unsigned char msg[] = { 'x2A', 'x20', 'x30', 'x20',
                                    'x49', 'x52', 'x20', 'x30',
                                    'x30', 'x31', 'x0D' };
            // Send message to device
            write(serial_port, msg, sizeof(msg));
            // Time for device to process
            std::system("sleep 0.25");
            // Close the serial port
            close(serial_port);
            // GPIO Off
            pin_off();
            return 0;   // success
        }
        // POWER OFF
        else if(strcmp(argv[2], "off") == 0)
        {
            // GPIO On
            pin_on();
            // Open the serial port READ-WRITE
            int serial_port = open("/dev/ttyS5", O_RDWR);
            // Load serial port settings
            settings(serial_port);
            // POWER OFF Message
            unsigned char msg[] = { 'x2A', 'x20', 'x30', 'x20',
                                    'x49', 'x52', 'x20', 'x30',
                                    'x30', 'x32', 'x0D' };
            // Send message to device
            write(serial_port, msg, sizeof(msg));
            // Time for device to process
            std::system("sleep 0.25");
            // Close the serial port
            close(serial_port);
            // GPIO Off
            pin_off();
            return 0;   // success
        }
        else if(argc == 2)
        {
            std::cout << "No argument passed!" << std::endl;
            std::cout << "Pattern: acer power <on/off>" << std::endl;
            return 1;   // failure
        }
        else if(argc > 3)
        {
            std::cout << "Too many arguments passed!" << std::endl;
            std::cout << "Pattern: acer power <on/off>" << std::endl;
            return 1;   // failure
        }
        else
        {
            std::cout << "Wrong argument! Passed: " << std::string(argv[2]) << std::endl;
            std::cout << "Pattern: acer power <on/off>" << std::endl;
            return 1;   // failure
        }
//...

Edit: Besides argc and argv[] values program doesn’t asign any variables

Edit 2.: Program is constructed of 2 argument actions and 3 arguments actions like this one mentioned it code I posted.

Source: Windows Questions C++

LEAVE A COMMENT