Originally Posted by
Adak
You had a null pointer assignment.
You are definitely on the right track, but I slightly disagree with your assessment. The problem in my opinion is not in his counting function (*ReturnCount = 0; is fine), but rather in main with (int* Count We don't want to declare count as a pointer; we want to declare it as an int and then pass it by reference to the counting function, which I noticed is exactly what you did in your correction, but you didn't point out that it was a crucial correction.
I went ahead and valgrinded the original:
Code:
==2109== Use of uninitialised value of size 8
==2109== at 0x40055D: count_match_char_in_array (foo.c:21)
==2109== by 0x4005CF: main (foo.c:46)
==2109==
==2109== Use of uninitialised value of size 8
==2109== at 0x40058E: count_match_char_in_array (foo.c:28)
==2109== by 0x4005CF: main (foo.c:46)
==2109==
==2109== Use of uninitialised value of size 8
==2109== at 0x400597: count_match_char_in_array (foo.c:28)
==2109== by 0x4005CF: main (foo.c:46)
==2109==
==2109== Use of uninitialised value of size 8
==2109== at 0x4005D7: main (foo.c:49)
==2109==
We have problems here:
Code:
#include <stdio.h>
#include <ctype.h>
/*
Function: count_match_char_in_array
Purpose:
Take input character array and count number of characters that match
an input character value without regard to case and return the count found
InputArray - Array to scan for matching characters
MatchChar - Character to match against
ReturnCount - Count of how many characters passed in MatchChar are found in InputArray
Returns:
Number of characters in InputArray
*/
int count_match_char_in_array(const char *InputArray, char MatchChar, int *ReturnCount)
{
int i;
// [ReturnCount] Use of uninitialised value from Count in main.
*ReturnCount = 0;
for(i=0;InputArray[i] != '\0';i++)
{
/* If we match the input char, bump the character count */
if(tolower(InputArray[i]) == MatchChar)
{
// [ReturnCount] Deference and assignment of uninitialised value from Count in main.
(*ReturnCount)++;
}
}
return(i);
}
/*
Purpose:
Test CountMatchCharInArray function
Will input test string and print out the matching count and the number
of characters in the input test string
*/
main()
{
int *Count;
int CharCount;
// [Count] Use of uninitialised value of size 8.
CharCount = count_match_char_in_array("Do you know the way to San Jose?", 'a',
Count);
// [Count] Use of uninitialised value of size 8. CharCount is initialized by count_match_char_in_array() call
printf("Found %d occurrences in a total length of: %d\n", *Count, CharCount);
}
Conceptually the problem is that declaring Count as pointer to int in main means that we don't actually hold information about the count. Only an int holds the actual count. If we want the function count_match_char_in_array() to return it as an out, we have to pass count by reference. That way, our function gets to alter the contents of Count because we have it's address, which is I think what we intended.