Not sure how to protect against a case where the user inputs a negative number?

Feb 12, 2021 at 5:28am
Hello!

We've been given test cases and one of the test cases is here you have to make sure that the user doesn't input a negative size for the 2D array. I'm not really sure what to do to protect against it. This is my code for that portion:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Puzzle::Puzzle(const Puzzle& rhs){
  m_size = rhs.m_size;

  if(rhs.m_size > 0){
    makeMem();

    for(int i = 0; i < m_size; i++){
      for(int j = 0; j < m_size; j++){
      m_table[i][j] = rhs.m_table[i][j];
      }
    }
  }
  //If user input size is less than 0 
    if (rhs.m_size < 0){
      m_table = nullptr;
      m_size = 0;
    }
}


I'm still getting a "terminate called after throwing an instance of 'std::bad_array_new_length'
what(): std::bad_array_new_length" error - which I'm assuming is from the test input being negative.
Feb 12, 2021 at 8:04am
It doesn't seems to be a problem with negative size. Rather how you create m_table. So what does makeMem() do? What is the type of m_size?
Feb 12, 2021 at 1:57pm
makeMem is supposed to allocate memory for char ** m_table.

Here is my makeMem function:



1
2
3
4
5
6
7
8
9
10
11
void Puzzle::makeMem(){

  if(m_size < 0){
    m_table = nullptr;
  }

  m_table = new char*[m_size];
  for(int i = 0; i < m_size; i++){
    m_table[i] = new char[m_size];
  }
}
Feb 12, 2021 at 2:44pm
(1)
What is the type of m_size?


(2) You're showing a copy constructor, so this presumably means that the original object being copied had a size < 0. Maybe one solution is to prevent this from happening (handle the error before it even gets to the point where a copy constructor is being called)?
Last edited on Feb 12, 2021 at 2:51pm
Topic archived. No new replies allowed.