You might call me crazy after reading this post, but I would really request you to trust me when you read what I say here. In my attempt to understand situations where memory leak or other errors could be caused, I wrote the following code and tried compiling on my pc,
#include <iostream>
using namespace std;
class game
{
int x;
public :
char *s;
char read();
char manipulation();
};
char game :: read()
{
char string[100];
cout<<"Enter name ";
cin>>string;
s = string;
cout<<"Name is "<<&s<<endl;
}
int main()
{
game games,games1;
// games.read();
cout<<"Name is "<<games.s<<endl;
return 0;
}
If i execute games.read() in my main, my anti-virus software BITDEFENDER shows me the following error, "BITDEFENDER has detected an infected item in c:/c++/inline.exe. Virus name : Gen:Variant.Graftor.51542. The file was disinfected for your protection"
inline.cpp is the name of my program.
If i remove that line "games.read()", it compiles fine. Is the pointer causing a memory leak somewhere?
Your anti-virus program just found a use-after-free vulnerability.
string is a local array.
You can't use it after read() exits.
If your system claims your code is a virus, then it's nothing to worry about in the sense that you are losing your mind; you are not.
Virus scanners will look for patterns of behaviors consistent with viruses and report them. They are not perfect, and non-virus behavior can look like a virus at times.
For instance, a classic virus strategy is to use invalid pointer writes to run arbitrary code. One of the first viruses used this and it's still a common strategy (I recall an IE update not long ago to fix this). So if you have a pointer error (as the previous poster noted) then it could look like a virus.
Related
I have some c++ code but I don't know what. For the purposes of example let's say it is:
//main.cpp
#include<iostream>
using namespace std;
int T[100];
int main()
{
for(int i = 0; i < 100; ++i)
T[i] = i;
int x;
cin>>x;
cout<<T[x]<<endl;
return 0;
}
I'm compiling it by cl /O2 /nologo /EHsc main.cpp and running by main < inFile.in. Let's say that inFile.in content is one number 500 and new line. The output is some random number because program reads memory under the address T+500 and printing it.
I want to get runtime error in such cases (any possibility of checking is something like this happened). Is this possible without access to main.cpp?
To be specific I'm running all this programmatically by Process class in C# in ASP.Net MVC Application. I want to check did program threw exception / read not reserved memory etc.
Is this a feature you want to use for development purposes only, or also in your production environment?
In case of development purposes only you may try to run your application under some tool for runtime checking (like Valgrind/Dr Memory), or change the way you compile it to include runtime debug checks (is not guaranteed to work in described case, but helps in many others). Keep in mind that this will make your application much slower (thus should be used only for applications under development)
When it comes to production environment, I am not aware of any way of doing what you want to - in general you can only count on OS segmentation fault in case of reading out of available memory (if you have luck - if you don't it'll "work").
For the exception thing, I'm not 100% sure I understand what you mean - is this "why did the program terminate" ? In such case on you might get a core dump of crashed application (in case of normal termination I assume you have return codes), and you can inspect it later to either get crash reason or possibly also try to recover some data. For instructions how to collect dumps on Windows, you may check out:
http://msdn.microsoft.com/en-us/library/windows/desktop/bb787181%28v=vs.85%29.aspx
However, this is also a feature that is more useful in development environment than in production.
If You can't modify above program's source then run it in 'outside' environment (shell) and get returned value and test it against 0 - any other value would me incorrect behavior.
It is also good to verify such programs' input data that you know it can't handle so rather than waiting for it to crash you can prevent it from happening.
If You could modify program then simple solution would be to use std::vector or std::deque which are similar but important is to use at() method and not the operator[] operator as the at() method checks bounds
#include<iostream>
#include<vector>
using namespace std;
std::vector<int> T(100);
int main()
{
for(int i = 0; i < 100; ++i)
T[i] = i;
int x;
cin>>x;
cout<<T.at(x)<<endl;
return 0;
}
if at() will be called with bad out-of-bound parameter then exception will be throw which You can catch like this:
try{
cin>>x;
cout<<T.at(x)<<endl;
}
catch(...)
{
cout << "exception while accessing vector's data" << endl;
}
i have problems with valgrind,
i created this class:
class shop {
private:
vector<vector<string> > products_;
public:
shop(string ProductFile);
FindMinPrice(string product);
}
//method in the cpp file
vector<string> shop::FindMinPrice(string product){
string ProductName=(string)products_[0][0];
}
i didn't write the entire code but its work fine with the GCC compiler.
when i run valgrind check it shows:
invalid read of size 8
and in eclipse it send me to the ProductName line.
what is wrong with the design ? and how so that the GCC compile and run but VALGRIND collapse?
thank you.
It appears that your products_ vector of vectors is empty, meaning that the access of element products_[0][0] is undefined behavior.
The unfortunate thing about undefined behavior is that your program may appear to work, and may even complete without any visible problems.
Using c-style cast in c++ is not a good practise.
Your shop method doesnt return any value.
I saw a similar, but still different question to this, so just to clarify this is not a dupe of 13428881 (Calling a function in an injected DLL).
What I have at the minute:
A DLL, injected into a target process, displaying a message box and fiddling around doing math.
What I want in the future:
A DLL which can manipulate and toy with the internals of the target process.
The next step towards achieving the desired manipulation is to call a method in a remote thread within the process I'm injecting into.
Let's take an example:
I have a C++ application, which has int main, let's say it looks like this:
int PrintText(string text)
{
cout << text;
return 1;
}
int main()
{
while (true)
{
PrintText("From the DLL");
}
}
Ok, so that's lovely, my target application is currently printing some text, and it seems to be doing so very happily. It's spamming it at an unbelievable rate, but I can slow it down using threads and sleeps etc if I need to. The fact is this isn't an issue, the code here hasn't been compiled or tested, and I've no intention of using this exact code. I'm actually working with a game.
Now, let's say I create a pointer to the method, PrintText, and that I know the address of it within that process. How do I go about calling it, externally, passing in arguments?
Locally, I believe it would look something like this:
int i;
int (*PrintSomeText)(string) = PrintText;
I could then call this function using a reference, like so:
i = operation("Text to be printed", PrintSomeText);
This should, by my theory, declare an integer called i, then define a pointer to a method which returns int, takes one string as a parameter, and the pointer stores the value of the pointer which was in PrintText. (Or something of that nature).
Very nice, so I can call my own functions via pointer, that's great, cracking in fact. I've truly astonished myself with this ability, and I do now feel like superman. I'll go save some babies or something, brb.
Back, so now I want to continue a little further, and take that next step. Let's say I know that the the method is at the address 100 in the target process (decimal, I will likely do it in hexadecimal, as I'm using CheatEngine / OllyDBG to find methods in the target process, but for this example we'll stay simple).
I presume that my injected DLL gets its own space entirely, does it have any higher access to the target process? How can I find this out?
Thanks for your time,
Josh
Edit: A small note, I'm going through the C++ tutorial book, and it's proven so far to be very useful. I've noticed that I forgot to include my operation method, so apologies for that being missing. If it's required, let me know. Thanks!
Edit nr 2: I've just made some compilable code to test this out, since I wrote most of this free hand reading from the book without an IDE, and the IDE has finally configured itself, so here is the code I'm currently working with
#include "stdafx.h"
#include <iostream>
using namespace std;
int PrintText(char * Text)
{
cout << Text << endl;
return 1;
}
int _tmain(int argc, _TCHAR* argv[])
{
int (*Print)(char*) = PrintText;
char Text[] = "Hello, world!";
PrintText(Text);
int x = (*Print)("Oh my word, it really works!");
cin.get();
return 0;
}
Note I haven't yet made it run indefinitely, so yeah, please excuse that, I'll add it shortly.
Dauphic is pretty much bang on, I have full control, as wildly was I'd like, to the target process. So, here's what I'm doing to call the target processes method (for any future readers interest):
Locate the method in memory. To do this, I first disabled ASLR (Address space layout randomization), then created a pointer to my method locally within the target program, before using the iostream to dump the pointer to screen, now I know the address of the method.
Create a typedef in the dll to be injected. This is where I got kinda stuck, but I know some guys who do this quite a lot, so I've managed to get it out of them. In my case, this is how the typedef looks:
typedef int __printPrototype(char* text);
Bind the address of the method in the target application, to a reproduction of it in the injected dll:
int (*Print)(char*);
Print = (__printPrototype*)0x0041121C;
Print("I'm injecting myself into you.");
Perfect!
Thanks to dauphic and a good friend named DarkstaR.
I'm working on this VST convolution plugin (Windows 7 64bit, VS2010) and I decided to try the Intel c++ compiler. I was in the process of optimizing the algorithm so I had a backup project in case of any screw ups and one I was doing experiments on. Both projects would compile and run with no problems. After installing the Intel compiler though the project I was experimenting on would cause a heap corruption error, so I start debugging to track down the problem but I can't find the line of code that causes it since the heap corruption error is not triggered during execution but after the termination of the DLL (there are also no access violations showed by the debugger).
At this point I start cutting out parts of the code to see if I can isolate the problem and I discover (obviously) that it was the class I was eperimenting on. Now here comes the weird part: I can change the code inside the methods but as soon as I add a variable to the backup class (the one that works fine), even an int, I get the heap corruption error, just a decleared and never referenced variable is enough.
This is the class CRTConvolver:
class CRTConvolver
{
public:
CRTConvolver();
~CRTConvolver();
bool Init(float* Imp, unsigned ImpLen, unsigned DataLen);
void doConv(float* input);
Buff Output;
int debug_test;
private:
void ZeroVars();
int Order(int sampleFrames);
template <class T> void swap ( T& a, T& b );
Buff *Ir_FFT,*Input_FFT,Output2,Tmp,Prev,Last;
float *Tail;
unsigned nBlocks,BlockLen,Bl_Indx;
IppsFFTSpec_R_32f* spec;
};
that "int debug_test;" makes the difference between a perfectly working VST module and a program that crashes on initialization from Cubase.
always for debugging purposes here are destr and constr:
CRTConvolver::CRTConvolver()
{
//IppStatus status=ippInit();
//ZeroVars();
}
CRTConvolver::~CRTConvolver()
{
//Init(NULL,NULL,NULL);
}
Here is what class Buff looks like:
class Buff {
public:
Buff();
Buff(unsigned len);
~Buff();
float* buff;
unsigned long length;
private:
void Init(unsigned long len);
void flush();
friend class CRTConvolver;
}
Buff::Buff()
{
length=NULL;
buff=NULL;
}
Buff::~Buff()
{
// flush();
}
basically this class if created and destructed does absolutely nothing, it just contains the length and buff variables. If I also bypass those two variable initializations the heap error goes away.
The software crashes on simple construction and subsequent destruction of the class CRTConvolver even though all it does is nothing, this is the part that really doesn't make sense to me...
As a side note, I create my CRTConvolver class like this:
ConvEng = new CRTConvolver[NCHANNELS];
If I declare it like this instead:
CRTConvolver ConvEng[NCHANNELS];
I get a stack corruption error around variable ConvEng.
If I switch back to Microsoft compiler the situation stays the same even when compiling and running the exact same version that could run without errors before....
I can't stress enough the fact that before installing the Intel compiler everything was running just fine, is it possible that something went wrong or there's an incompatibility somewhere ?
I'm really running out of ideas here, I hope someone will be able to help.
thanks
Going to guess, since the problem is most likely undefined behavior, but in some other place in your code:
Obey the rule of three. You should have a copy constructor and assignment operator. If you're using std containers, or making copies or assignments, without these you run into trouble if you delete memory inside the destructor.
It looks to me that the CRTConvolver default constructor (used in creating an array) is writing to memory it doesn't own. If the Intel compiler has different class layout rules (or data alignment rules), it might be unmasking a bug that was benign under the Microsoft compiler's rules.
Does the CRTConvolver class contain any instances of the Buff class?
Updated to respond to code update:
The CRTConvolver class contains four instances of Buff, so I suspect that is where the problem lies. It could be a version mismatch -- the CRTConvolver class thinks that Buff is smaller than it really is. I suggest you recompile everything and get back to us.
Is there any way a program can crash before main()?
With gcc, you can tag a function with the constructor attribute (which causes the function to be run before main). In the following function, premain will be called before main:
#include <stdio.h>
void premain() __attribute__ ((constructor));
void premain()
{
fputs("premain\n", stdout);
}
int main()
{
fputs("main\n", stdout);
return 0;
}
So, if there is a crashing bug in premain you will crash before main.
Yes, at least under Windows. If the program utilizes DLLs they can be loaded before main() starts. The DllMain functions of those DLLs will be executed before main(). If they encounter an error they could cause the entire process to halt or crash.
The simple answer is: Yes.
More specifically, we can differentiate between two causes for this. I'll call them implementation-dependent and implementation-independent.
The one case that doesn't depend on your environment at all is that of static objects in C++, which was mentioned here. The following code dies before main():
#include <iostream>
class Useless {
public:
Useless() { throw "You can't construct me!"; }
};
static Useless object;
int main() {
std::cout << "This will never be printed" << std::endl;
return 0;
}
More interesting are the platform-dependent causes. Some were mentioned here. One that was mentioned here a couple of times was the usage of dynamically linked libraries (DLLs in windows, SOs in Linux, etc.) - if your OS's loader loads them before main(), they might cause your application do die before main().
A more general version of this cause is talking about all the things your binary's entry point does before calling your entry point(main()). Usually when you build your binary there's a pretty serious block of code that's called when your operating system's loader starts to run your binary, and when it's done it calls your main(). One common thing this code does is initializing the C/C++ standard library. This code can fail for any number of reasons (shortage of any kind of system resource it tries to allocate for one).
One interesting way on for a binary to execute code before main() on windows is using TLS callbacks (google will tell you more about them). This technique is usually found in malware as a basic anti-debugging trick (this trick used to fool ollydbg back then, don't know if it still does).
The point is that your question is actually equivalent to "is there a way that loading a binary would cause user code to execute before the code in main()?", and the answer is hell, yeah!
If you have a C++ program it can initialize variables and objects through functions and constructors before main is entered. A bug in any of these could cause a program to crash.
certainly in c++; static objects with contructors will get called before main - they can die
not sure about c
here is sample
class X
{
public:
X()
{
char *x = 0;
*x = 1;
}
};
X x;
int main()
{
return 0;
}
this will crash before main
Any program that relies on shared objects (DLLs) being loaded before main can fail before main.
Under Linux code in the dynamic linker library (ld-*.so) is run to supply any library dependancies well before main. If any needed libraries are not able to be located, have permissions which don't allow you to access them, aren't normal files, or don't have some symbol that the dynamic linker that linked your program thought that it should have when it linked your program then this can cause failure.
In addition, each library gets to run some code when it is linked. This is mostly because the library may need to link more libraries or may need to run some constructors (even in a C program, the libraries could have some C++ or something else that uses constroctors).
In addition, standard C programs have already created the stdio FILEs stdin, stdout, and stderr. On many systems these can also be closed. This implies that they are also free()ed, which implies that they (and their buffers) were malloc()ed, which can fail. It also suggests that they may have done some other stuff to the file descriptors that those FILE structures represent, which could fail.
Other things that could possibly happen could be if the OS were to mess up setting up the enviromental variables and/or command line arguments that were passed to the program. Code before main is likely to have had to something with this data before calling main.
Lots of things happen before main. Any of them can concievably fail in a fatal way.
I'm not sure, but if you have a global variable like this :
static SomeClass object;
int main(){
return 0;
}
The 'SomeClass' constructor could possibly crash the program before the main being executed.
There are many possibilities.
First, we need to understand what actually goes on before main is executed:
Load of dynamic libraries
Initialization of globals
One some compilers, some functions can be executed explicitly
Now, any of this can cause a crash in several ways:
the usual undefined behavior (dereferencing null pointer, accessing memory you should not...)
an exception thrown > since there is no catch, terminate is called and the program end
It's really annoying of course and possibly hard to debug, and that is why you should refrain from executing code before main as much as possible, and prefer lazy initialization if you can, or explicit initialization within main.
Of course, when it's a DLL failing and you can't modify it, you're in for a world of pain.
Sort of:
http://blog.ksplice.com/2010/03/libc-free-world/
If you compile without standard library, like this:
gcc -nostdlib -o hello hello.c
it won't know how to run main() and will crash.
Global and static objects in a C++ program will have their constructors called before the first statement in main() is executed, so a bug in one of the constructors can cause a crash.
This can't happen in C programs, though.
It depends what you mean by "before main", but if you mean "before any of your code in main is actually executed" then I can think of one example: if you declare a large array as a local variable in main, and the size of this array exceeds the available stack space, then you may well get a stack overflow on entry to main, before the first line of code executes.
A somewhat contrived example would be:
int a = 1;
int b = 0;
int c = a / b;
int main()
{
return 0;
}
It's unlikely that you'd ever do something like this, but if you're doing a lot of macro-magic, it is entirely possible.
class Crash
{
public:
Crash( int* p )
{ *p = 0; }
};
static Crash static_crash( 0 );
void main()
{
}
I had faced the same issue. The root-cause found was.. Too many local variables(huge arrays) were initialized in the main process leading the local variables size exceeding 1.5 mb.
This results in a big jump as the stack pointer is quite large and the OS detects this jump as invalid and crashes the program as it could be malicious.
To debug this.
1. Fire up GDB
2. Add a breakpoint at main
3. disassemble main
4. Check for sub $0xGGGGGGG,%esp
If this GGGGGG value is too high then you will see the same issue as me.
So check the total size of all the local variables in the main.
Sure, if there's a bug in the operating system or the runtime code. C++ is particularly notorious for this behaviour, but it can still happen in C.
You haven't said which platform/libc. In the embedded world there are frequently many things which run before main() - largely to do with platform setup - which can go wrong. (Or indeed if you are using a funky linker script on a regular OS, all bets are off, but I guess that's pretty rare.)
some platform abstraction libraries override (i personally only know of C++ libraries like Qt or ACE, which do this, but maybe some C libraries do something like that aswell) "main", so that they specify a platform-specific main like a int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ); and setup some library stuff, convert the command line args to the normal int argc, char* argv[] and then call the normal int main(int argc, char* argv[])
Of course such libraries could lead to a crash when they did not implement this correctly (maybe cause of malformed command line args).
And for people who dont know about this, this may look like a crash before main
Best suited example to crash a program before main for stackoverflow:
int main() {
char volatile stackoverflow[1000000000] = {0};
return 0;
}