Access Violation on char array - c++

I'm getting an access violation on a char array I just created using new.
DispatchCommand(char* cmdStr)
{
// Dispatch
for(int i = 0; i < sizeof(_lpCommands); i++)
{
const int len = strlen(_lpCommands[i].szCommand);
char* cmdblip = new char[len + 1];
memcpy(&cmdblip, cmdStr, len);
cmdblip[len] = '\0'; // Access Violation
if(strcmp(cmdblip, _lpCommands[i].szCommand) == 0)
{
if(strlen(cmdStr) > strlen(_lpCommands[i].szCommand))
(*_lpCommands[i].cbCallback)(&cmdStr[strlen(_lpCommands[i].szCommand)]);
else
(*_lpCommands[i].cbCallback)("");
delete cmdblip;
return;
}
delete cmdblip;
}
// Error and return
*Out::ServerInfo<<"Command not found!"<<ENDL;
}
_lpCommands is an array of Command structures:
struct Command
{
char* szCommand;
CommandCallback cbCallback;
};
The produced error message is:
Unhandled exception at 0x012219cf in Program.exe: 0xC0000005: Access
violation writing location 0x66647366.
This was a rewrite of similar code which was using memcmp, which ended up giving me an access violation as well without be doing a memcpy.
What gives?

Don't pass &cmdblip to memcpy. You should pass a pointer to the destination buffer, not a pointer to that pointer. Pass cmdblip instead.
Edit: I agree that in general, std::string should be used in C++. Still, the technical reason this code crashes is that memcpy corrupts the cmdblip pointer, making it point on a memory location that is actually made of the first 4 bytes of the copied string. Then, cmdblip[len] results in a memory location that is not within the allocated buffer (or any other legally allocated buffer), hence the crash. So, if you want to write better code, use C++ classes. And if you want to understand why the given code crashed, consider the above.

The only possible helpful answer to this question is "Use std::string". The specific problem you are having now will simply re-occur, or an identical one, every time you modify this function or write another like it. The only way to solve the problem in the general case is to move to a class-based solution, which is kindly provided for you as Standard. For example, your current code is exception unsafe, on top of whatever is giving you an access violation, not to mention that it's unreadable and begging for a number of other errors, such as off-by-one, not properly NULL terminating, double deletes, and memory leaks. Oh, and UB because you delete what you new[].

Related

Acces Violation 0xCCCCCCCC [duplicate]

For the past 2 days I've been stuck on a violation which I can't seem to get to go away.
I've used break points and located where the error is, but I'm just hoping one of you will know what the issue is without me having to copy+paste all my code -.-
I'm getting
First-chance exception at 0x1027cb1a (msvcr100d.dll) in Escape.exe: 0xC0000005: Access violation writing location 0xcccccccc.
Unhandled exception at 0x1027cb1a (msvcr100d.dll) in Escape.exe: 0xC0000005: Access violation writing location 0xcccccccc.
Now, a quick google search makes me think there's something peculiar going on. All the search results talk about pointers not actually pointing anywhere (0xccccccccc is a low memory address?).
I'm yet to use pointers in my code but either way I'll paste the function and point out the line the exception gets thrown (in bold):
void mMap::fillMap(){
for(int i = 0; i <= 9; i++){
for(int z = 0; z <= 19; z++){
Tile t1; // default Tile Type = "NULLTILE"
myMap[i][z] = t1;
}
}
}
Now myMap is a 2d array of type Tile. I had this working a couple of days ago until I added some other classes and it all stopped working!
Either an uninitialized pointer, or a pointer stored in memory that's been freed. I think cccccccc is the first and cdcdcdcd is the second, but it varies with compiler/library implementation.
For your particular code, probably myMap hasn't been allocated yet, then myMap[0][0] would result in an access attempt to 0xcccccccc.
It can also happen that myMap is the beginning of your class, and the class pointer was uninitialized:
class mMap
{
Tile myMap[10][20];
public:
void f() { myMap[0][0] = 0; }
};
mMap* what;
what->f(); // what is an invalid pointer
This happens because the member function is not virtual, so the compiler knows what code to run and passes the object pointer as a hidden parameter. Eventually the compiler emits a calculation like:
this + offsetof(Whatever::myMap) + z * sizeof(myMap[0]) + i * sizeof(myMap[0][0])
this, being uninitialized, is 0xcccccccc. Evidently the offsetof part is zero, and i and z are both zero the first time through your loop, so you get 0xcccccccc + 0 + 0 + 0 as the memory address.
To debug this, use the call stack and find the function that called fillMap. Then check in that function where the pointers used for member access (->) came from.
On MSVC++ and in debug mode, the debugging memory allocator sets all returned memory to 0xcccccccc, as a way to find cases of undefined behavior. In all likelihood, you never initialized myMap , or some of the pointers inside of myMap. Check your initialization code for bugs.
For all of the answers and comments happening in this question, here are good references about memory fills in Visual C++:
http://msdn.microsoft.com/en-us/library/bebs9zyz.aspx
When and why will an OS initialise memory to 0xCD, 0xDD, etc. on malloc/free/new/delete?
Had similar error when I tried to fill string value in table element of my own-class type with for-loop. I declared 1000 elements in that table, so I've put something like that:
for (int i = 0; i <= 1000; i++)
{
TAble[i].name = "Some Guy";
TAble[i].age = 4;
}
Unfortunately as with string it occurred that I'm perhaps insisting on fillinf element that doesn't exist witch is element number 1000 in table. I managed to solve this by changing loop header, deleting equal sign before 1000.
Try to see whether you're not trying to call something that doesnt exist.

C++ Error :Unhandled exception : Access violation reading location [duplicate]

For the past 2 days I've been stuck on a violation which I can't seem to get to go away.
I've used break points and located where the error is, but I'm just hoping one of you will know what the issue is without me having to copy+paste all my code -.-
I'm getting
First-chance exception at 0x1027cb1a (msvcr100d.dll) in Escape.exe: 0xC0000005: Access violation writing location 0xcccccccc.
Unhandled exception at 0x1027cb1a (msvcr100d.dll) in Escape.exe: 0xC0000005: Access violation writing location 0xcccccccc.
Now, a quick google search makes me think there's something peculiar going on. All the search results talk about pointers not actually pointing anywhere (0xccccccccc is a low memory address?).
I'm yet to use pointers in my code but either way I'll paste the function and point out the line the exception gets thrown (in bold):
void mMap::fillMap(){
for(int i = 0; i <= 9; i++){
for(int z = 0; z <= 19; z++){
Tile t1; // default Tile Type = "NULLTILE"
myMap[i][z] = t1;
}
}
}
Now myMap is a 2d array of type Tile. I had this working a couple of days ago until I added some other classes and it all stopped working!
Either an uninitialized pointer, or a pointer stored in memory that's been freed. I think cccccccc is the first and cdcdcdcd is the second, but it varies with compiler/library implementation.
For your particular code, probably myMap hasn't been allocated yet, then myMap[0][0] would result in an access attempt to 0xcccccccc.
It can also happen that myMap is the beginning of your class, and the class pointer was uninitialized:
class mMap
{
Tile myMap[10][20];
public:
void f() { myMap[0][0] = 0; }
};
mMap* what;
what->f(); // what is an invalid pointer
This happens because the member function is not virtual, so the compiler knows what code to run and passes the object pointer as a hidden parameter. Eventually the compiler emits a calculation like:
this + offsetof(Whatever::myMap) + z * sizeof(myMap[0]) + i * sizeof(myMap[0][0])
this, being uninitialized, is 0xcccccccc. Evidently the offsetof part is zero, and i and z are both zero the first time through your loop, so you get 0xcccccccc + 0 + 0 + 0 as the memory address.
To debug this, use the call stack and find the function that called fillMap. Then check in that function where the pointers used for member access (->) came from.
On MSVC++ and in debug mode, the debugging memory allocator sets all returned memory to 0xcccccccc, as a way to find cases of undefined behavior. In all likelihood, you never initialized myMap , or some of the pointers inside of myMap. Check your initialization code for bugs.
For all of the answers and comments happening in this question, here are good references about memory fills in Visual C++:
http://msdn.microsoft.com/en-us/library/bebs9zyz.aspx
When and why will an OS initialise memory to 0xCD, 0xDD, etc. on malloc/free/new/delete?
Had similar error when I tried to fill string value in table element of my own-class type with for-loop. I declared 1000 elements in that table, so I've put something like that:
for (int i = 0; i <= 1000; i++)
{
TAble[i].name = "Some Guy";
TAble[i].age = 4;
}
Unfortunately as with string it occurred that I'm perhaps insisting on fillinf element that doesn't exist witch is element number 1000 in table. I managed to solve this by changing loop header, deleting equal sign before 1000.
Try to see whether you're not trying to call something that doesnt exist.

Why are we able to access unallocated memory in a class?

I am sorry if I may not have phrased the question correctly, but in the following code:
int main() {
char* a=new char[5];
a="2222";
a[7]='f'; //Error thrown here
cout<<a;
}
If we try to access a[7] in the program, we get an error because we haven't been assigned a[7].
But if I do the same thing in a class :
class str
{
public:
char* a;
str(char *s) {
a=new char[5];
strcpy(a,s);
}
};
int main()
{
str s("ssss");
s.a[4]='f';s.a[5]='f';s.a[6]='f';s.a[7]='f';
cout<<s.a<<endl;
return 0;
}
The code works, printing the characters "abcdfff".
How are we able to access a[7], etc in the code when we have only allocated char[5] to a while we were not able to do so in the first program?
In your first case, you have an error:
int main()
{
char* a=new char[5]; // declare a dynamic char array of size 5
a="2222"; // assign the pointer to a string literal "2222" - MEMORY LEAK HERE
a[7]='f'; // accessing array out of bounds!
// ...
}
You are creating a memory leak and then asking why undefined behavior is undefined.
Your second example is asking, again, why undefined behavior is undefined.
As others have said, it's undefined behavior. When you write to memory out of bounds of the allocated memory for the pointer, several things can happen
You overwrite an allocated, but unused and so far unimportant location
You overwrite a memory location that stores something important for your program, which will lead to errors because you've corrupted your own memory at that point
You overwrite a memory location that you aren't allowed to access (something out of your program's memory space) and the OS freaks out, causing an error like "AccessViolation" or something
For your specific examples, where the memory is allocated is based on how the variable is defined and what other memory has to be allocated for your program to run. This may impact the probability of getting one error or another, or not getting an error at all. BUT, whether or not you see an error, you shouldn't access memory locations out of your allocated memory space because like others have said, it's undefined and you will get non-deterministic behavior mixed with errors.
int main() {
char* a=new char[5];
a="2222";
a[7]='f'; //Error thrown here
cout<<a;
}
If we try to access a[7] in the program, we get an error because we
haven't been assigned a[7].
No, you get a memory error from accessing memory that is write-protected, because a is pointing to the write-only memory of "2222", and by chance two bytes after the end of that string is ALSO write-protected. If you used the same strcpy as you use in the class str, the memory access would overwrite some "random" data after the allocated memory which is quite possibly NOT going to fail in the same way.
It is indeed invalid (undefined behaviour) to access memory outside of the memory you have allocated. The compiler, C and C++ runtime library and OS that your code is produced with and running on top of is not guaranteed to detect all such things (because it can be quite time-consuming to check every single operation that accesses memory). But it's guaranteed to be "wrong" to access memory outside of what has been allocated - it just isn't always detected.
As mentioned in other answers, accessing memory past the end of an array is undefined behavior, i.e. you don't know what will happen. If you are lucky, the program crashes; if not, the program continues as if nothing was wrong.
C and C++ do not perform bounds checks on (simple) arrays for performance reasons.
The syntax a[7] simply means go to memory position X + sizeof(a[0]), where X is the address where a starts to be stored, and read/write. If you try to read/write within the memory that you have reserved, everything is fine; if outside, nobody knows what happens (see the answer from #reblace).

Accessing deleted array- access violation exception

I wanted to access deleted array to see how the memory was changed it works till I deleted really big array then I get access violation exception. Please do not care about cout I know they are slow but I will get rid of them.
When I do it for 1000 elements array it is ok, when I do it for 1000000 i get an exception. I know that this is weird task but my teacher is stubborn and I can't find out how to deal with that.
EDIT: I know that I never should access that memory, but I also know that there is probably trick he will show then and tell that I am not right.
long max = 1000000;// for 10000 i do not get any exception.
int* t = new int[max];
cout<<max<<endl;
uninitialized_fill_n(t, max, 1);
delete[] t;
cout<<"deleted t"<<endl;
int x;
cin>>x;//wait little bit
int one = 1;
long counter = 0;
for(long i = 0; i < max; i++){
cout<<i<<endl;
if(t[i] != 1){
cout<<t[i]<<endl;
counter++;
}
}
That state of "deleted" memory is undefined, to access memory after delete is UNDEFINED BEHAVIOUR (meaning, the C++ specification allows "anything" to happen when you access such memory - including the appearance of it "working" sometimes, and "not working" sometimes).
You should NEVER access memory that has been deleted, and as shown in your larger array case, it may not work to do so, because the memory may no longer actually be available to your process.
You are not allowed to access to a released buffer
Accessing memory that is no longer in use results in undefined behaviour. You will not get any consistent patterns. If the original memory has not been overwritten after it became invalid, the values will be exactly what they used to be.
I find the answer to this similar question to be very clear in explaining the concept with a simple analogy.
A simple way to mimic this behaviour is to create a function which returns a pointer to a local variable, for example:
int *foo(){
int a=1;
return &a;
}

Access violation writing location 0xcccccccc

For the past 2 days I've been stuck on a violation which I can't seem to get to go away.
I've used break points and located where the error is, but I'm just hoping one of you will know what the issue is without me having to copy+paste all my code -.-
I'm getting
First-chance exception at 0x1027cb1a (msvcr100d.dll) in Escape.exe: 0xC0000005: Access violation writing location 0xcccccccc.
Unhandled exception at 0x1027cb1a (msvcr100d.dll) in Escape.exe: 0xC0000005: Access violation writing location 0xcccccccc.
Now, a quick google search makes me think there's something peculiar going on. All the search results talk about pointers not actually pointing anywhere (0xccccccccc is a low memory address?).
I'm yet to use pointers in my code but either way I'll paste the function and point out the line the exception gets thrown (in bold):
void mMap::fillMap(){
for(int i = 0; i <= 9; i++){
for(int z = 0; z <= 19; z++){
Tile t1; // default Tile Type = "NULLTILE"
myMap[i][z] = t1;
}
}
}
Now myMap is a 2d array of type Tile. I had this working a couple of days ago until I added some other classes and it all stopped working!
Either an uninitialized pointer, or a pointer stored in memory that's been freed. I think cccccccc is the first and cdcdcdcd is the second, but it varies with compiler/library implementation.
For your particular code, probably myMap hasn't been allocated yet, then myMap[0][0] would result in an access attempt to 0xcccccccc.
It can also happen that myMap is the beginning of your class, and the class pointer was uninitialized:
class mMap
{
Tile myMap[10][20];
public:
void f() { myMap[0][0] = 0; }
};
mMap* what;
what->f(); // what is an invalid pointer
This happens because the member function is not virtual, so the compiler knows what code to run and passes the object pointer as a hidden parameter. Eventually the compiler emits a calculation like:
this + offsetof(Whatever::myMap) + z * sizeof(myMap[0]) + i * sizeof(myMap[0][0])
this, being uninitialized, is 0xcccccccc. Evidently the offsetof part is zero, and i and z are both zero the first time through your loop, so you get 0xcccccccc + 0 + 0 + 0 as the memory address.
To debug this, use the call stack and find the function that called fillMap. Then check in that function where the pointers used for member access (->) came from.
On MSVC++ and in debug mode, the debugging memory allocator sets all returned memory to 0xcccccccc, as a way to find cases of undefined behavior. In all likelihood, you never initialized myMap , or some of the pointers inside of myMap. Check your initialization code for bugs.
For all of the answers and comments happening in this question, here are good references about memory fills in Visual C++:
http://msdn.microsoft.com/en-us/library/bebs9zyz.aspx
When and why will an OS initialise memory to 0xCD, 0xDD, etc. on malloc/free/new/delete?
Had similar error when I tried to fill string value in table element of my own-class type with for-loop. I declared 1000 elements in that table, so I've put something like that:
for (int i = 0; i <= 1000; i++)
{
TAble[i].name = "Some Guy";
TAble[i].age = 4;
}
Unfortunately as with string it occurred that I'm perhaps insisting on fillinf element that doesn't exist witch is element number 1000 in table. I managed to solve this by changing loop header, deleting equal sign before 1000.
Try to see whether you're not trying to call something that doesnt exist.