1

When I output the return value of the InitialSeedFinder function seen below (aka value stored in the seed variable), I get some random ascii chars that corrupt the expected string value. This only happens if the buffer is more 2 chars (ie. it works for when the order variable is less than 3).

This error is being introduced in the while loop seen in the code below...

Can someone explain WHY this is happening? does it have something to do with how the read() function works?

string InitialSeedFinder(int order, string fileName){ string seed; ifstream inputStream; Map<string, int> frequencyMap; inputStream.open(fileName.c_str()); int offset = 0; inputStream.clear(); char* buffer = new char [order]; //get all k char sequence while (inputStream.get() != EOF) { inputStream.seekg(offset); inputStream.read(buffer, order); string key(buffer); if (frequencyMap.containsKey(key)) { frequencyMap[key] = frequencyMap[key] + 1; } else { frequencyMap.put(key, 1); } offset++; } inputStream.close(); //go through and find the most frequent key int greatestFrequency = 0; int frequency = 0; foreach(string key in frequencyMap) { frequency = frequencyMap[key]; if (frequency > greatestFrequency) { greatestFrequency = frequencyMap[key]; seed = key; } } return seed; } 
1
  • The description of problem smells distinctly of writing beyond the bounds of allocated memory.Have you profiled your code with memory analyzer like valgrind? Commented Aug 20, 2012 at 5:57

1 Answer 1

1

read() does not add a terminator to the end if the string. However, when casting a char* to a string it requires a nul terminator. When your buffer was short you got lucky and there was a zero at the end, when it was longer there was non-zero data.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks, that helped, I changed the conversion to string key(buffer, order); and it works now
You should get the number of bits read and use that instead, read() returns that value.
How do I find the number of bits read? What is wrong with specifying the number of letters read instead (as I initially did by using order to specify length)??

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.