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;
}
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);
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With