Reputation: 267
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;
}
Upvotes: 3
Views: 2196
Reputation: 1
instead of returning -1 and 0 return something else such as length instead of -1 and i instead of 0 and change condition in main function accordingly. then program will give output every time.(don't know logic but it works for me)
Upvotes: 0
Reputation: 56049
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;
}
Upvotes: 1
Reputation: 8150
It's a classic buffer overflow. You need to limit the length of the data read in:
scanf("%14s", x);
Alternately, you can tell scanf to allocate the buffer for you:
char* x;
scanf("%as", &x);
...
checkArray(x, 15);
This will allocate a buffer long enough for any string you give it. (Limitations of course on physical memory and bad people sending your application 10GB of data).
This string is dynamically allocated so it will need to be freed:
free(x);
Upvotes: 0
Reputation: 75130
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);
Upvotes: 5