jotape
jotape

Reputation: 319

Simple if statement in c that doesn't work

Can anyone tell me why this code crashes? It's simple, if the length of the string is > than 16, ask again for a string. It works if I write control = 1 inside the if statement, but it should work the same without it, 'cause the value of control at that point is 1, am I right? thans (I'm learning)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int
main(void)
{
    int control = 1;
    char word[16] ;
    printf("Enter a word: ");

    while(control == 1)
    {
        scanf("%s", word);

        int len = strlen(word);
        printf("Lenght is: %d\n", len);

        if (len >= 16) 
        {
            printf("Word lenght to long, enter a new one: ");
        }

        else
        {
            control = 0;
        }

    }
    printf("This is the word: %s\n", word );

}

Upvotes: 1

Views: 299

Answers (3)

pb2q
pb2q

Reputation: 59637

As others have noted, your fundamental problem is that you're allocating 16 characters for the string, and scanf will happily allow you to write past those 16 characters into memory that doesn't belong to you.

Be aware that C will allow you to do this with arrays generally, and understand how standard C strings work: you need to null-terminate them, meaning that you'll always need an extra space in the array for a null-terminating character \0.

There is a way to limit scanf with respect to C strings, using a field width specifier with %s, like so:

char input[17];  // room for 16 characters plus null-terminator

// here scanf will stop after reading 16 characters:
scanf("%16s", input);

With this code, you can safely use scanf to fill your string with no more than 16 characters, and scanf will null-terminate the string for you.

But as others have also noted, scanf is pretty poor at handling user input. It's usually better to use fgets and manage the input string on your own, piece-by-piece.

Upvotes: 1

user82238
user82238

Reputation:

char word[16] allocates 16 bytes of store for a string.

scanf() then reads a string into that store.

If you read in more than the amount of allocated store, memory is corrupted after the end of the store.

That's why you crash.

Upvotes: 8

Code-Apprentice
Code-Apprentice

Reputation: 83577

The problem is that if the user types more than the 15 characters which you have allocated space for, then the computer will merrily write all of them in memory past the end of your array. This will result in "undefined behavior" including crashing your program.

Upvotes: 2

Related Questions