String is full of garbage

Hello I have this code here what I need to do is count the number of chars in this string. The word can be as long as WORD_LENGTH. While debugging in gdb the string is full of garbage after the chars I set. I tried to malloc the memory but I get the same result. Each word will end with the '\n' as they will be read from a text file. Thank you.

The string is char *word = "Adam\n";

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int get_word_length(const char *word)
{
	int count = 0;
	
	if (word == NULL)
	{
		printf ("NULL pointer..\n");
		return 0;
	}
	
	for(int i = 0; i < WORD_LENGTH; i ++)
	{
		if (isalpha(word[i]) && (word[i]) != '\n')
		{
			count++;
		}
	}
	return count;
}
I just realized their is a function in the string.h header so I will use that but I would like to know what I did wrong for future reference Thanks.
The end of a string is marked with a null character '\0'. You need to make the loop stop when such a character is found.
Hi

You should consider NULL character to terminate the loop

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int get_word_length(const char *word)
{
	int count = 0,i;
	
	if (word == NULL)
	{
		printf ("NULL pointer..\n");
		return 0;
	}
	
	for( i = 0; i < WORD_LENGTH && word[i] != '\0' ; i ++)
	{
		if (isalpha(word[i]))
		{
			count++;
		}
	}
	return count;
}


if you consider \n as end of character for your string replace '\0' in your for loop with '\n'

 
for( i = 0; i < WORD_LENGTH && word[i] != '\n' ; i ++)
Topic archived. No new replies allowed.