c++ code compiles but failed at runtime
The code below compiles but after clicking on first button it breaks with msg
Unhandled exception at 0x0133ae9a in deming.exe: 0xC0000005: Access violation writing location 0x014aedbd.
Is it a c++ error as i am novice or is it dragonsdk i use ?
//====================================================
// App.cpp
//====================================================
#include "DragonFireSDK.h"
#include <string.h>
int Picture;
int OnClick(int value)
{
char* image = "Images/image";
image = strcat(image,"_");
Picture = PushButtonAdd(image, 10, 100, OnClick, 1);
return 0;
}
void AppMain()
{
// Application initialization code goes here. Create the items / objects / etc.
// that your app will need while it is running.
Picture = PushButtonAdd("Images/Logo", 10, 100, OnClick,开发者_如何学JAVA 1);
}
You're failing here:
char* image = "Images/image";
image = strcat(image,"_");
You're trying to modify a constant string.
The reason of your problem is wrong imagination of what strcat does. It is appending second buffer to the first - in this case your first buffer is static, so appending to it obviously fails. You should use something like
char* image = "Images/image";
char* fullname = new char[strlen(image)+2];
strcpy(fullname, image);
strcat(fullname,"_");
Also don' forget to delete[] fullname
after you are done with the buffer.
You might find useful documentation for strcat (and other functions) in here
You migh also consider using C++ std::string, as they do it all for you, and if you need c-style strings, you can always get them via c_str() method.
You are trying to append a character to a string literal (i.e. "Images/image"
), and this results in an access violation, since it's stored in read-only memory.
You should instead do:
char image[100]="Images/image"; // make it large enough to contain all the further modifications you plan to do
strcat(image,"_");
This will work because you are working with a local buffer, that you can freely change.
To avoid other mistakes with string literals you should always use const char *
to point to them, the compiler won't allow you to even try to modify them.
By the way, since you're working in C++, there's no reason not to use C++ strings instead of char *
& co.
const char* image = "Images/image";
is more accurate. You cannot append or modify it any way. Use std::string.
std::string image("Images/image");
image.append(1,'_');
精彩评论