My C++ program compiles and works up until I call this function from main():
int uword(){fstream infile("numbers.txt");
fstream exfile("wordlist.txt");
string numb[numoflines];
string lines[numoflines];
number = 1;
line = 1;
for(int i=0;i<numofline;++i)
{
getline (infile,number);
numb[i] = number; //I think this is causing the problem
getline (exfile,line);
lines[i] = line; //This too
}
infile.close();
exfile.close();
string yourword;
Something here causes it to crash, in the debug it pops up with "An access violation (Segmentation Fault) raised in your program."
EDIT: My mistake was using !infile.eof in the for loop.
Not a direct answer, but I believe it's a good one...
Use The Debugger! GDB should suspend at the exact line when the segmentation fault happens, thus giving you a very good hint about what the error is.
The getline function does not work the way you think it works.
Also, there could be more than numoflines lines in infile.
Related
I have been running into this EXC_BAD_ACCESS issue a lot lately when developing in C++ using Xcode. This time, I can't figure out what is wrong though.
I have this function that should be simple enough, just a way to count how many lines are in a file:
int getNumLines(string file)
{
int lineCount = 0;
string line;
ifstream textFile;
textFile.open(file);
if( textFile.is_open() && !textFile.ios_base::fail() )
{
while(getline(textFile, line))
{
lineCount++;
}
}
textFile.close();
return lineCount;
}
Every time I run my code, I get this line of errors leading back to the fstream class file, and the error code:
Thread 1: EXC_BAD_ACCESS (code=1, address=0x7000000070)
Here is where this error leads:
I'm not sure what's causing this issue. Zombie objects don't seem to help me find the source of the problem, or perhaps I am just not understanding how to enable them properly.
Thanks for all your help. I found the issue to be how I was handling arrays in the objects I created. I moved everything over to std::array instead of int* and my memory errors went away.
Wrote a program that has a method that opens a popen command to a temporary file, reads the output and parses for use somewhere else in the program. If the command succeeds, program works as expected. However, if the popen tries a command that fails, the file still has a valid pointer but when the program tries to read the data with fgets the program seg faults.
Function body:
std::map<std::string,size_t> cols;
const char* command = command_string.c_str();
if (FILE *fp = popen(command,"r")) {
char buff[linesize];
std::vector<std::string> list;
std::cout << "here, popen succeeded\n";
std::cout << fp << '\n';
while (fgets(buff,linesize,fp)) {
std::cout << "here, fgets succeeded\n";
std::string data(buff);
list.push_back(data);
}
parse_cols(list);
pclose(fp);
}
else {
std::cout << "Failed to open bash shell when trying to run command\n";
std::exit(EXIT_FAILURE);
}
With the output:
here, popen succeeded
0x1cc2430
sh: my_command: command not found
Segmentation fault (core dumped)
Is it possible to handle this error? It's a somewhat useful error, but I'd like to be able to handle it rather then just relying on the seg fault. I tried looking at the FILE struct, but seems to be different for different C library versions.
Popen is a beast. It only returns nullptr when fork or pipe fails, but in your case they do not.
However, your program should not segfault. When shell returns failure, you should be reading from a valid (albeit empty) stream. Than fgets() returns NULL because end of file occurs while no characters have been read.
Than you are calling parse_calls - a function we do not see - but I have reasons to believe it can't handle the empty list. Crash stacks could be of further help when it comes to pinpointing the actual problem, which is not in popen or fgets.
Hi I am facing memory fault with my code. I used gdb and found out where memory fault occurs. But I am not able to solve that. The lines of code where memory fault occurs is below. Please help me friends.
void CJob::print_parm_file(){
int m_nFuncid;
CCmdset* pCmdset = NULL;
const int size=1024;
char fname[80];
char dbg_buf[size]="";
unsigned int i, gotit=0;
for (i=0; i < entries(); i++)
{
pCmdset = (CCmdset*) at(i);
//RWCollectableString *cmdset = (RWCollectableString *)pCmdset->at(0);
//RWCString m_Function=cmdset->data();
CXmlobj *xobj = (CXmlobj *)pCmdset->at(0);
cout <<"The value of m_name.data() //segfault issue is : " << xobj->m_name << endl;
cout <<"The value of m_name.data() //segfault issue is : " << xobj->m_name.data() << endl;
RWCString m_Function=xobj->m_name.data(); //segmentation fault occurs in this line
I have printed the value of m_name.data() to check its value. when i tried printing its value, segmentation fault occured in cout statements itself.
NOTE : This issue is happening only in Linux server. The code is working perfect in Unix server without any issue.
Please help me ! Thanks !!!
My educated guess is that m_name is of type std::string. There is no guarantee that a null character terminates the character sequence pointed by the value returned by data(). Simply put, your prints may access more elements than that string actually contains which causes this segmentation fault.
Try adding a \0 character at the end of the string, or replace data() with c_str() which is guaranteed to be null-terminated.
Did you first establish that xobj is valid?
CXmlobj *xobj = (CXmlobj *)pCmdset->at(0); // if xobj is invalid
xobj->m_name.data(); // ... then this will invoke undefined behavior
The simplest thing to try is just assign that string variable to a temporary string variable and see what happens. If you still get a segmentation fault, then the problem is more than likely that xobj is not pointing to a valid CXmlobj.
this gives me a segmentation fault:
for (int i=0; !file.eof();i++)
{
getline(file,line);
roughInput.lines[i].split(line);
}
and this doesn't
for (int i=0; i<2;i++)
{
getline(file,line);
roughInput.lines[i].split(line);
}
from my understanding for should increase i by one until the end of file, right?
since i couldn't find much example on i-net, is there a better solution?
Your loop is probably running one time too many. file.eof() will not return false until after you have tried to read while you are at the end of the file. You probably want to put the check in between the getline call and the split:
getline(file, line);
if (!file.eof())
roughInput.lines[i].split(line);
and fix the loop logic accordingly.
However, a better solution would be to grow roughInput.lines dynamically, so that you don't get a seg fault if the file is longer than you expect.
what i'm writing is simple, well, it should be, but i'm getting this error and i don't know what else to do, my code look like this
int main()
{
char *option;
while(strcmp(option,"exit")!=0){
int opt = GetSystemDefaultUILanguage();
std::string lang;
switch(opt)
{
case 3082:
lang = "number 3082";
break;
case 1033:
lang = "number 1033";
break;
}
std::cout<<lang<<'\n';
std::cin>>option;
}
}
when i compile it there isn't errors, but when i run it, i get a this error
Project xxxx raised exception class EAccessViolation with message 'Access violation at address zzzzz'.Process stopped. Use Step or Run to continue.
EDITED:
This is my full code, now is more simple, but still the same result.
even if i try with an if/else statement it wont work, need some help here, thanks
Your program will always get an access violation because of the following lines:
char *option;
while(strcmp(option,"exit")!=0){
std::cin>>option;
You never initialize the pointer option, but then try to use it. Change your code to this:
int main()
{
std::string option;
while(option != "exit")
{
int opt = GetSystemDefaultUILanguage();
std::string lang;
switch(opt)
{
case 3082:
lang = "number 3082";
break;
case 1033:
lang = "number 1033";
break;
}
std::cout<<lang<<std::endl;
std::cin>>option;
}
}
I can't tell you the cause of the specific run-time error you're seeing, but I call tell you what's wrong with your program: hardcoded paths to user directories. Localized names are just one of a myriad of things that can go wrong with trying to guess the paths yourself.
DON'T DO THAT. Instead, read environment variables or call Shell APIs to find out where this particular user wants temporary data stored (or documents, pictures, desktop icons, etc).
Have a look at getenv("TEMP") and ShGetSpecialFolderPath
Your problem is this line:
std::cin>>option;
The variable option is declared as an uninitialized pointer to a character. Thus in the above statement, you are reading data into an unknown location.
Why do you use C style strings (char *) and C++ std::string?
You should get rid of C style strings (unless they are constant).
Try this:
#include <iostream>
#include <string>
int main(void)
{
std::string option;
do
{
std::cout << "Type exit to end program." << std::endl; // endl will flush output buffer
std::getline(cin, option); // Input a text line into "option".
} while (option != "exit"); // C-style string, used as a constant.
return 0;
}
You wrote
BlockquoteProject xxxx raised exception class EAccessViolation with message 'Access violation at address zzzzz'.Process stopped. Use Step or Run to continue.
So why don't you pause your program before crash, go to the location and put a breakpoint? If you still can't cope with that than upload your code to a filesharing server and give us the link ;)