简体   繁体   中英

segmentation fault, address out of bounds

I'm writing a function that takes a string of input from the user until newline is hit, then parses the string into each word and puts them into an array.

The problem I get is when you first start the program, if you enter in whitespace as input, it gets a segmentation fault. If you put in anything else, it runs fine. Then if you put just whitespace as input after that, it runs fine as well.

Here is a snippet of the function:

#define MAXARGS 10

char buf[100];
char cmd[MAXARGS][100];
char *bp = NULL;
int i, n;

for (i = 0; i < MAXARGS; i++)
    strcpy(cmd[i], "");

fputs(" >> ", stdout);
fgets(buf, sizeof(buf), stdin);
bp = buf;

for (i = 0; i < MAXARGS; i++)
{
    sscanf(bp, "%99s%n", cmd[i], &n);
    bp += n;
    while (*bp == ' ') // segfault is here
        bp += 1;
}

I'm on Windows running MinGW with MSYS. When I run it through GDB I get:

Program received signal SIGSEGV, Segmentation fault.
0x0040152d in command () at main.c:46
46                              while (*bp == ' ')
(gdb) print bp
$1 = 0x47291c <Address 0x47291c out of bounds>
(gdb) print *bp
Cannot access memory at address 0x47291c

...but I'm not familiar with GDB so I don't know what else to check

sscanf should return the number of matched items, if it can't match anything it will return 0 and n will be left with what it had before, and you end up using n to increment a pointer.
Check what sscanf returns before using n and don't use it if it returns 0

Print n . I suspect it gets a really unexpected value (perhaps negative ? although that's unlikely).

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