简体   繁体   中英

How can i detect “out of bound error” in C program with GDB?

I wrote this program in C, adding an intentional error on purpose.

The program calculates the sum of 5 numbers entered by the user, and displays the result on the screen.

I compiled it with "gcc -Wall -Wextra -Werror -ansi -pedantic -g" and works fine.

But it has an error.

In the last repetition of the cycle, the program evaluates a[N], which is not defined!

I'd like to know how to spot this kind of error using GDB

When i use " set check range on " i get this messange "warning: the current range check setting does not match the language." and nothing happens...

This is the code to debug:

#define N 5
#include <stdio.h>


void read(float*);


int main(void) {

    float a[N], s;

    int i;

    printf("Enter %d numbers: ", N);
    read(a);

    i = -1; 
    s = 0;

    while (i != N) {
        i = i + 1;
        s = s+a[i];
    }

    printf("The sum is : %.2f \n", s);

    return 0;
}


void read(float*a) {

    int n = 0;

    while (n!=N) { 
        scanf("%f",&a[n]);
        n++;
    }

}

I think this is your problem:

while (i != N) {
    i = i + 1;
    s = s+a[i];
}

N is defined as 5 , so when i is 4, the condition is true. i is then incremented to 5, and s += a[i]; is executed. Just use a for loop instead, or use do {} while :

for (i=0;i<N;++i)
    s += a[i];
//or
i = 0;
do {
   s += a[i];
} while (++i != N);

Either way. Personally, I find the for loop more readable


To answer your question (using gdb):

  • You've compiled using the -g flag, so run `gdb compiled_file_name
  • In gdb, set a break-point in the while loop ( b <line-nr> [condition] )
  • start the program ( run )
  • use step or next to step through the code
  • use pi to check the value of i every time you hit the while condition, and every time you use i as offset ( a[i] )

For more details, docs for gdb are available. It takes some time, but it's well worth it. gdb is an excellent debugger

The answer to this particular error is that the loop increments i and then accesses a at index i, without an intervening check. So when i equals N - 1 when it starts the loop, it's incremented to N and used in the array.

In general, gcc's -fsanitize=bounds option should be helpful for these errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM