Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Char Array Userinput check length

Tags:

arrays

c

scanf

I read in a char array with scanf and want to check if the length is bigger than 15. It works only sometimes. (If not I get an error --> core dumped.)

My Code:

#include <stdio.h>

int checkArray(char string[], int length) {
    int i;
    for(i=0; string[i] != '\0'; i++);
    if(i > length) {
        return -1;
    }
    return 0;
}

int main ()
{
    const int length = 15;
    char x[15];
    scanf("%s", x);
    if(checkArray(x, length) == -1) {
        printf("max. 15 chars!");
        return 1;
    }
    return 0;
}
like image 469
user1069968 Avatar asked Feb 19 '26 05:02

user1069968


2 Answers

x can never (legally) be more than 14 characters big because you have it in a buffer of size 15 (14 spaces for characters, one for the NUL-terminator), so it is pointless to try to check if it is less than 15 characters long.

If you try to store a string bigger than 14 in it, it will overrun the array and hopefully cause an error like the one you are experiencing. Optionally make your array bigger so it can actually hold more than 15 characters and put a width-specifier for %s:

char x[30];

scanf("%29s", x); // read a maximum of 29 chars (replace 29 if needed
                  // with one less than the size of your array)

checkArray(x, 15);
like image 70
Seth Carnegie Avatar answered Feb 20 '26 18:02

Seth Carnegie


When scanf reads in a string longer than 14 characters (reserving one for the null terminator), it's corrupting memory. Then, there are a couple problems with your checkArray() method:

int checkArray(char string[], int length) {
    int i;

    // This next line could as well be a call to `strlen`.
    // But you shouldn't let it access `string` when `i` is >= `length`. 
    for(i=0; string[i] != '\0'; i++);

    // This should be `>=`.  If `i` is 15, you accessed (in the loop above)
    // `string[15]`, which is past the end of the array.
    if(i > length) {
        return -1;
    }

    return 0;
}
like image 32
Kevin Avatar answered Feb 20 '26 20:02

Kevin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!