Reputation: 1117
I'm beginning with C language and I'm learning it through a platform that checks automatically the code I write (e.g., it gives me some task and after uploading the code it checks whether what I wrote gives meaningful results).
So far all has been working fine, but I'm stuck with one problem that, to my eye I've solved, but after uploading the code and running it, an error occurs that I frankly don't understand.
TASK: Print the longest word in a sentence, and its length.
My Attempt:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char str[80], word[80];
fgets(str, 80, stdin);
char *token;
//tokenizing array str
token = strtok(str, " ");
while( token != NULL )
{
if(strlen(word) < strlen(token) )
{
strcpy(word, token);
}
token = strtok(NULL, " ");
}
printf("%s %d", word, strlen(word));
return 0;
}
For instance if one writes
hello my name is jacksparrowjunior goodbye
one gets
jacksparrowjunior 17
And the error is this:
TEST
PASSED
==20760== Conditional jump or move depends on uninitialised value(s)
==20760== at 0x4006B9: main (004799.c:18)
==20760== Uninitialised value was created by a stack allocation
==20760== at 0x400660: main (004799.c:6)
==20760==
==20760== Conditional jump or move depends on uninitialised value(s)
==20760== at 0x4006E5: main (004799.c:18)
==20760== Uninitialised value was created by a stack allocation
==20760== at 0x400660: main (004799.c:6)
==20760==
The other thing I noticed, is that if I change
char str[80], word[80];
fgets(str, 80, stdin);
to
char str[1000], word[1000];
fgets(str,1000, stdin);
I get an error after running the program in my computer.
Upvotes: 2
Views: 2516
Reputation: 796
The error message is both helpful and arcane. Notice the reference to a Conditional and an uninitialized. So you should go and look at conditions ("if tests") in your code.
The next lines in the error give clues where to look: lines 18 and 6.
Upvotes: 0
Reputation: 224
Depending on the given Data and without testing I would guess you should initialize str and word to ""
[...]
char str[80] = "";
char word[80] = "";
fgets(str, 80, stdin);
[...]
Upvotes: 2