System.AccessViolationException in Visual Studio 2008 - c++

// diskbin.cpp : main project file.
#include "stdafx.h"
#include <windows.h>
#include <iostream>
#include <fstream>
#include <conio.h>
#include <stdio.h>
#include <sys/stat.h>
using namespace std;
int main( int argc, char *argv[] )
{
//code
if(stat("key.pc.db", &filek) ==0 )
sizek=filek.st_size;
if(stat("seek.pc.db", &files) ==0 )
sizes=files.st_size;
sizek=sizek/sizeof(int);
sizes=sizes/sizeof(int);
int i,min,max,mid;
int *s=new int[sizes];
int *hit=new int[sizes];
//code
}
When I run this program in Visual Studio 2008, I am not getting any error but when I run the cmd opens and then closes followed by a pop up window which says:
"An unhandled exception of type 'System.AccessViolationException' occurred in diskbin.exe
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt." What could be the issue? Have I not allocated s and hit properly?
Thanks!

It's crashing because you're using uninitialized variables:
int sizes, sizek;
struct stat files, filek;
ofstream ofs;
if(stat("key.pc.db", &filek) ==0 )
sizek=filek.st_size;
if(stat("seek.pc.db", &files) ==0 )
sizes=files.st_size;
sizek=sizek/sizeof(int);
sizes=sizes/sizeof(int);
if stat() fails, you use an uninitialized sizek.
Depending on the uninitialized memory, your next statement will crash:
int *s=new int[sizes];
because sizes can be negative or a very large number and the new will fail.
Check the error returned by stat(), although it's possible the file key.pc.db is not found, causing the function to fail.

Related

readdir hangs up if libpocofoundation is linked with my tiny app

I've started debbuging on some app, which hangs up in a loop based on readdir call.
Step by step I've cut everything but problem code, this is it:
So, in basic, it shows name of first entry and nothing more. It even does not exits, just waiting for something.
Also, I've found, that if don't lin it against libpocofoundation, it works.
But I have to do it because it used in the original app.
I'm a little bit confused, I don't use Poco in this example in any way, but it some way hangs it.
Please help me, I'm in panic :D
#include <iostream>
#include <sys/types.h>
#include <dirent.h>
#include <cstring>
#include <string>
#include <fcntl.h>
using namespace std;
int main(int argc, char *argv[])
{
const char TMP_DIR[] = "/opt";
DIR *dir = opendir(TMP_DIR);
std::cerr
<< readdir(dir)->d_name
<< readdir(dir)->d_name
<< std::endl;
return 0;
}
So... I don't know why it was happening. So I just dropped libpoco.

Using chdir() Causes Segmentation Fault

I'm writing a batch emulator as a personal project. I'm trying to implement the cd command using chdir() from unistd.h. However, using this causes a segfault.
main.cpp:
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include <stdio.h>
//Custom headers
#include "splitting_algorithm.hpp"
#include "lowercase.hpp"
#include "chdir.hpp"
//Used to get and print the current working directory
#define GetCurrentDir getcwd
using namespace std;
int main(int argc, char* argv[])
{
string command;
//Begin REPL code
while (true)
{
//Prints current working directory
cout<<cCurrentPath<<": ";
std::getline(std::cin, command);
vector<string> tempCommand = strSplitter(command, " ");
string lowerCommand = makeLowercase(string(strSplitter(command, " ")[0]));
//Help text
if(tempCommand.size()==2 && string(tempCommand[1])=="/?")
{
cout<<helpText(lowerCommand);
}
//Exit command
else if(lowerCommand=="exit")
{
return 0;
}
else if(lowerCommand=="chdir")
{
cout<<string(tempCommand[1])<<endl;
chdir(tempCommand[1]);
}
else
cout<<"Can't recognize \'"<<string(tempCommand[0])<<"\' as an internal or external command, or batch script."<<endl;
}
return 0;
}
chdir.cpp:
#include <cstdlib>
#include <string>
#include <unistd.h>
void chdir(std::string path)
{
//Changes the current working directory to path
chdir(path);
}
Strangely enough, using cout to get the path for chdir works perfectly fine. How do I fix this?
You have recursive, unterminated behaviour in Your code. This overflows the stack.
Try to insert breakpoint in void chdir(std::string path) and see what happens.
You will see that the function chdir calls itself, and in turn calls itself again, and again and... well, segmentation fault.
Also, try to see what "call stack" is in the debugger, this issue is very visible there.
You should invoke the underlying chdir function using
::chdir(path.c_str());
or you will just call your own method again.
In unistd.h, chdir is defined as:
int chdir(const char *);
So you must call it with a const char* argument or the compiler will search for another function called "chdir" which take a std::string argument and use that instead.

Set read cursor fails

I am using boost to read a file
But when I set seekg to a position (~20000) in the file,
I get a runtime error
Microsoft C++ exception:
boost::exception_detail::clone_impl`<`boost::exception_detail::error_info_injector`<`std::ios_base::failure>>> at memory location 0x00EEC874.
Code:
ifstream if("file.bin",std::ios::binary)
if (if.is_open())
{
boost::iostreams::stream<boost::iostreams::mapped_file_source>is(fs);
is.seekg(20000, is.beg); //error is here
//// read
}
That code shouldn't compile. If it does, file a bug report with the compiler vendor.
if is a reserved keyword.
Assuming you messed up the code sample, (because you also had missing ;), it should just work but you may just have missing files/error handling:
Live On Coliru
#include <boost/iostreams/device/mapped_file.hpp>
#include <boost/iostreams/stream.hpp>
#include <fstream>
#include <iostream>
int main() {
std::ifstream ifs("main.cpp",std::ios::binary);
if (ifs.is_open())
{
boost::iostreams::stream<boost::iostreams::mapped_file_source> is("main.cpp");
if (is.seekg(200, is.beg))
std::cout << is.rdbuf();
}
}

segmentation fault reading json file

I need to read the information contained in a json file like this:
{"first":10, "second":"0", "P1":"1.e-20","P2":"1000","P3":"1000","P4":"1000","P5":"1"}
Since I do not have experience with this issue, I started by playing with the short code you can see below these lines. It does compile with no problem but it gives a segmentation fault back upon execution. The file general.json is in the same folder. The information contained in the json file is correctly printed in the screen if I comment the last line. Could anyone tell me what am I doing wrong?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fstream> // fstream.h in old versions of g++
#include <iostream> //para cout
#include <sstream>
#include <json/json.h>
using namespace std;
int main() {
struct json_object *new_json, *json_arr, *json_reg, *json_field;
string line;
stringstream jsonfile;
ifstream json("file.json", ios::in);
{getline(json, line); do {jsonfile << line;} while (getline(json, line));}
json.close();
cout << jsonfile.str().c_str();
new_json=json_tokener_parse(jsonfile.str().c_str());
json_field=json_object_object_get(json_reg, "first");
}
You are using the json_reg pointer without initializing it and the function dereferences it. You are (most likely) using json-c where:
json_object_object_get calls json_object_object_get_ex on the object
json_object_object_get_ex does switch(jso->o_type) dereferencing an invalid pointer

MinGW portability

I'm completely new to C++, but I have created a minor program, looking to port the program to other computers, but when I "install" the program I get this error...-static-libgcc -static-libstdc++ missing, is there a file I should be including in the program itself, or is this a library I have to install on each computer? The computers that I expect to run the program will be windows xp. Source code of the file is as follows:
#include <stdlib.h>
#include <windows.h>
#include <direct.h>
#include <string.h>
#include <string>
#include <iostream>
using namespace std;
int main(int argc, const char *argv[])
{
_chdir("C:\\Program Files\\NCHSoftware\\Talk\\");
string number = "start talk.exe -dial " + std::string(argv[1]+4);
system(number.c_str());
exit;
return 0;
}
They are shared lib's that would need to be on the host computer.
To learn how to compile a static version;
See here: http://gcc.gnu.org/onlinedocs/gcc/Link-Options.html
Read the "-static-libgcc" & "-static-libstdc++" sections.