Home > Net >  I did not set a breakpoint but entered a breakpoint. I used vscode to debug the program
I did not set a breakpoint but entered a breakpoint. I used vscode to debug the program

Time:12-03

I did not set breakpoints. My main program controls the acquisition of input and then performs verification. The first input is OK, but after one input content verification, the second verification will enter breakpoint mode. The program breaks in the sentence shown in the picture. Then I need to click Continue two or three times to continue the normal execution of the program. I want to ask why this happens?

No breakpoints

Code of calling function with breakpoint in main program:

  /* Verify whether the entered value is each value between 1 and max_value */
  while(checkForDuplicationForNums(key, key_length_m)  /* Check whether the entered value is repeated */
    || checkElemExceedsMax(key, key_length_m) 
    || checkNumWithinMaxNotAppear(key, key_length_m)) {
        illegalInputPrompt();
        getInputNumArrayByGetchHaveSpaces(key_string, key);
  }

Code snippet for breakpoint occurrence:

int checkForDuplicationForNums(int nums[], int max_value){
  int* within_max_value = (int *)calloc(max_value, sizeof(int)); 
  for(int i=0; i<max_value; i  ) {
    /* nums : 0~m-1 */
    within_max_value[nums[i]]  ;
  }
  for(int i=0; i<max_value; i  ) {
    if(within_max_value[i] > 1) {
      return 1; 
    }
  }
  free(within_max_value);
  return 0;
}

The location of the strange breakpoint: free(within_max_value);

Program execution effect

The max_value is always 11 during the program running.

The first input makes the nums:

int nums[11] = {0, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9};

The second input makes the nums:

int nums[11] = {0, 11, 2, 3, 4, 5, 6, 7, 8, 9, 10};

Then the program breaking. nums[1] exceeds the value range of my expected input value: 1~11.

CodePudding user response:

In the second loop iteration, the line

within_max_value[nums[i]]  ;

is writing to the array within_max_value out of bounds.

Since you stated that max_value has the value 11 in both function calls, this means that i will have the value 10 in the last loop iteration.

According to the information provided in your question, in the second function call, num[10] will have the value 11. This means that the line

within_max_value[nums[i]]  ;

is equivalent to

within_max_value[11]  ;

in the last loop iteration of the second function call.

That expression is accessing the array within_max_value out of bounds, because valid indexes are 0 up to and including 10. The index 11 is out of bounds.

By writing to the array out of bounds, you are probably corrupting heap memory, which causes the next call to free to generate an exception, which causes the debugger to stop at that line.

  • Related