I know that this question has been asked lots of times. But, in my case, the error is not always present so I think it might be different. I am using C++, Visual Studio 2013, Windows 7 x64.
Here's the relevant code:
void writeDATAToFile(const char *fname, string title, const VecDoub& spec_x, const VecDoub& spec_y, const VecDoub& freq)
{
ofstream of;
of.open(fname, ios_base::out);
if (!of.is_open())
{
return;
}
of << "somename" << endl;
of << "WAVES/S" << "\t" << title << endl;
of << "BEGIN" << endl;
for (int i=0; i<spec_x.size(); i++)
{
of << spec_x[i] << "\t\t\t" << spec_y[i] << "\t\t\t" << freq[i]<<endl;
}
of << "END" << endl;
of.close();
}
This function is supposed to write the spectrum data (calculated earlier in the program) and write it to a file. Some spectrum data won't cause a problem, some will. The error is in the for loop.
Here is the error window:
You're passing 3 vectors to your function:
const VecDoub& spec_x, const VecDoub& spec_y, const VecDoub& freq
but you never check that they have the same size.
In your loop (not the "second" loop as you said in your question, there's just one loop in the code you posted), you're iterating over spec_x and you use the same index i to index into the other two vectors.
What if one or both of your other two vectors have a smaller size than spec_x? Then you're indexing out of bounds which would cause the error you're seeing.
The error message clearly says it is trying to read something it shouldn't be.
You code loops thus:
for (int i=0; i<spec_x.size(); i++)
{
of << spec_x[i] << "\t\t\t" << spec_y[i] << "\t\t\t" << freq[i]<<endl;
}
This assumes spec_x, spec_y and freq are the same size.
You could check this before looping and throw an error if this
precondition doesn't hold.
You could loop up to the smallest size of all three.
You could leave this function as is and put checks where you populate the data originally.
Note - the debugger is trying to help you. If you hit "break" it will five you a call stack, and then you should be able to see exactly which variable is causing the problem.
Related
I'm using this code to output nodes of a huffman tree to a text file with a certain formatting. All the node outputs within the if block run as expected, but the first output in the else block is missing the '0' fill character after the "L:". It should output "L:076" but instead is outputting "L: 76". The cout looks correct but the text file isn't. All future loops through the else block output like they should, it's only the first loop that is missing the fill character. Here's a picture of my output
void preOrder(node* tree, std::ofstream& of) {
if (tree->label > 0) {
of << "I:" << tree->label << " ";
}
else {
std::cout.width(3);
std::cout << std::right;
std::cout.fill('0');
std::cout << int(tree->ch) << std::endl;
of << "L:";
of << of.fill('0');
of << std::right;
of << int(tree->ch);
of << " ";
return;
}
preOrder(tree->left, of);
preOrder(tree->right, of);
}
From cppreference.com:
The second form (2) sets fillch as the new fill character and returns the fill character used before the call.
"The second form" is the non-const version, that applies here. So my guess (I never used fill myself and I cannot compile your code as it is) would be that the call is correctly applied and then you put the old fill character (blank space presumably) to the stream, because you do:
of << of.fill('0');
Also, I noticed that you dont set the width of of.
Because you're hiding something naughty from us.
#include <iostream>
int main()
{
std::cout.width(3);
std::cout << std::right;
std::cout.fill('0');
std::cout << 3 << std::endl;
return 0;
}
Outputs 003 (live example).
Please provide an MCVE and I'll edit my answer to help you.
I am writing code for a project in my computer science course and I am testing my algorithm to see if it works and how fast it is. I know that the algorithm works because when I launch the program in Visual Studio 2013, I get the correct output. But, when I launch the .exe from the Visual Studio projects folder in the command line or from windows explorer, the first two cout statements are displayed correctly, but the cout statements during the for loop are not displayed at all. Again this only happens when I launch the .exe outside of Visual Studio. It isn't a big problem, but I wonder what's going on here. Thanks.
Here is int main() (The first 2 couts work and the others don't):
int main() {
// declare input stream for reading dctnryWords.txt
ifstream inFile;
// create a pointer to memory in the heap
// where each word in the dictionary will be stored
string* words = new string[DICTIONARY_SIZE];
// create a vector of forward_lists to hold
// adjacent words for each word in the dictionary
vector< list<string> > adjacents(DICTIONARY_SIZE);
// open dctnryWords.txt
inFile.open("dctnryWords.txt");
// load words into RAM
cout << "Loading words into RAM took: "
<< time_call([&] { copyDictionary(inFile, words); })
<< "ms\n";
cout << "Finding adjacent words took: "
<< time_call([&] { searchAdjacents(words, adjacents); })
<< "ms\n";
for (int i = 0; i < DICTIONARY_SIZE; i++) {
if (adjacents[i].size() >= 25) {
cout << words[i] << "(" << adjacents[i].size()
<< "): ";
for (list<string>::const_iterator j = adjacents[i].cbegin(); j != adjacents[i].cend(); j++) {
cout << *j << " ";
}
cout << endl << endl;
}
}
return 0;
}
I'll bet a nickel your program isn't finding "dctnryWords.txt" when you launch it elsewhere... because it's going to look in the current directory, which is likely different when you run it outside of VS.
I'm very new to programming in C++ but I'm trying to write some code which filters a specific word from a string and then takes a specific action. For some reason the code does not see the text inside the string.
printf("%s \n", data.c_str());
cout << data;
This shows absolutely nothing - meaning I cannot use .find or write it to a file.
printf("%s \n", data);
This shows exactly what I need.
I am writing the code into data with assembly:
mov data, EDX
Why is that I can only use the the last method?
Edit:
Data is initiated as:
std::string data;
If a pointer to a string is null all subsequent calls to cout
stop working
const char* s=0;
cout << "shown on cout\n";
cout << "not shown" << s << "not shown either\n";
cout << "by bye cout, not shown\n";
The two function calls are not equivalent, as \n at printf flushes the stream. Try with:
cout << data << endl;
Be sure you used
#include <string>
in your file header. With this in place you should be able to use
std::cout << data << endl;
with no issues. If you're using a global namespace for std you may not need the std::, but I'd put it anyway to help you debug a it faster and eliminate that as a possible problem.
In Short
You will have a problem with cout, if you don't put a linebreak at it's end!
In Detail
Try adding an endl to your cout (e.g. std::cout << data << std::endl), or use following instruction to activate "immediate output" for cout (without it needing a linebreak first).
std::cout << std::unitbuf;
Complete example:
std::cout << std::unitbuf;
std::cout << data;
// ... a lot of code later ...
std::cout << "it still works";
Sidenote: this has to do with output buffering, as the name unitbuf suggests (if you want to look up what is really happening here).
This way it is also possible to rewrite the current line, which is a good example, where you would need this ;-)
Practical example
using namespace std;
cout << "I'm about to calculate some great stuff!" << endl;
cout << unitbuf;
for (int x=0; x<=100; x++)
{
cout << "\r" << x << " percent finished!";
// Calculate great stuff here
// ...
sleep(100); // or just pretend, and rest a little ;-)
}
cout << endl << "Finished calculating awesome stuff!" << endl;
Remarks:
\r (carriage return) puts the curser to the first position of the line (without linebreaking)
If you write shorter text in a previously written line, make sure you overwrite it with space chars at the end
Output somewhere in the process:
I'm about to calculate some great stuff!
45 percent finished!
.. and some time later:
I'm about to calculate some great stuff!
100 percent finished!
Finished calculating awesome stuff!
I can't seem to find any solution for this.
I have a type 'route' that contains a matrix.if I do:
cout << route << endl;
it works it prints the memory
but if I try
cout << route[1][1] << endl;
program just ends without any error or anything.
debug says:
"(Suspended : Signal : SIGSEGV:Segmentation fault)"
here is the code:
//structure is a type I created
Structure ***route = list->searchRoute(startPoint, destination, time);
//should return a matrix
cout << "Avaible routes: \n" << endl;
for(int i = 0; i < 5;i++)
cout << route[1][1]->startPoint << endl;
Segmentation fault usually implies that you are accessing memory you are not supposed to access. What is probably happening is that our "matrix" is probably too small to have a block in the second row/ second column, so an error is thrown when you try to access that location(because you do not own it). Make sure you are allocating route correctly and at the right size.
I am using the following function to loop through a couple of open CDB hash tables. Sometimes the value for a given key is returned along with an additional character (specifically a CTRL-P (a DLE character/0x16/0o020)).
I have checked the cdb key/value pairs with a couple of different utilities and none of them show any additional characters appended to the values.
I get the character if I use cdb_read() or cdb_getdata() (the commented out code below).
If I had to guess I would say I am doing something wrong with the buffer I create to get the result from the cdb functions.
Any advice or assistance is greatly appreciated.
char* HashReducer::getValueFromDb(const string &id, vector <struct cdb *> &myHashFiles)
{
unsigned char hex_value[BUFSIZ];
size_t hex_len;
//construct a real hex (not ascii-hex) value to use for database lookups
atoh(id,hex_value,&hex_len);
char *value = NULL;
vector <struct cdb *>::iterator my_iter = myHashFiles.begin();
vector <struct cdb *>::iterator my_end = myHashFiles.end();
try
{
//while there are more databases to search and we have not found a match
for(; my_iter != my_end && !value ; my_iter++)
{
//cerr << "\n looking for this MD5:" << id << " hex(" << hex_value << ") \n";
if (cdb_find(*my_iter, hex_value, hex_len)){
//cerr << "\n\nI found the key " << id << " and it is " << cdb_datalen(*my_iter) << " long\n\n";
value = (char *)malloc(cdb_datalen(*my_iter));
cdb_read(*my_iter,value,cdb_datalen(*my_iter),cdb_datapos(*my_iter));
//value = (char *)cdb_getdata(*my_iter);
//cerr << "\n\nThe value is:" << value << " len is:" << strlen(value)<< "\n\n";
};
}
}
catch (...){}
return value;
}
First, I am not familiar with CDB and I don't believe you include enough details about your software environment here.
But assuming it is like other database libraries I've used...
The values probably don't have to be NUL-terminated. That means that casting to char* and printing it will not work. You should add a 0 byte yourself.
So malloc cdb_datalen + 1 and set the last character to 0. Then print it.
Better yet, use calloc and it will allocate memory already set to zero.