0

I am trying to initialise these two character arrays inside a constructor. The error is with the character arrays buf and clientip, the others are fine. I have added the code of the entire constructor below:

class server : public udp {

public:
    server() {

        clientLength = 0;
        buf[1024] = {};
        bytesIn = 0;
        count = 0;
        clientIp[256] = {};
        portnumber = 0;
    }

private:
    
    int clientLength = sizeof(client);
    char buf[1024];
    int bytesIn;
    int count = 0;
    char clientIp[256];
    unsigned short portnumber = 70000;

The warning is that:

*(error) Array 'buf[1024]' accessed at index 1024, which is out of bounds. [arrayIndexOutOfBounds]

(error) Array 'clientIp[256]' accessed at index 256, which is out of bounds. [arrayIndexOutOfBounds]*

How can I solve this problem?

2
  • It told you exactly what the problem is: buf[1024] = {}; in your constructor is accessing element 1024, which is out of bounds. Remove the [1024]. Better yet, move all of that to the initialization section of the constructor, or assign the default values in the private section. Commented Aug 22, 2020 at 18:41
  • @sweenish Thanks alot for your answer. Can you show me in code what you mean for the first part of the solution Commented Aug 22, 2020 at 18:58

1 Answer 1

1

buf[1024] = {}; does not what you want. It will access the 1024th element of buf and default initialize just this element, but it is out of bounds.

What you probably want:

class server : public udp {

public:
    server() : clientLength(), buf(), bytesIn(), count(), clientIp(), portnumber(){
    }

You should always prefer the member initialize list when possible.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.