visual c++代码可编译,但在运行时失败

visual c++ code compiles but failed at runtime

本文关键字:运行时 失败 编译 c++ 代码 visual      更新时间:2023-10-16

下面的代码可以编译,但在单击第一个按钮后,它会中断消息

deming.exe中0x0133ae9a处未处理的异常:0xC0000005:写入位置0x014aedbd时发生访问冲突。

这是一个c++错误,因为我是新手,还是我使用的dragonsdk?

//====================================================
// 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, 1);
}

您在这里失败了:

char* image = "Images/image";
image = strcat(image,"_");

您正试图修改常量字符串。

问题的原因是对strcat功能的错误想象。它将第二个缓冲区附加到第一个缓冲区——在这种情况下,第一个缓冲区时是静态的,所以附加到它显然失败了。你应该使用类似的东西

char* image = "Images/image";
char* fullname = new char[strlen(image)+2];
strcpy(fullname, image);
strcat(fullname,"_");

另外,不要忘记在处理完缓冲区后使用delete[] fullname。您可能会在这里找到strcat(和其他函数(的有用文档

您还可以考虑使用C++std::string,因为它们都是为您完成的,如果您需要C样式的字符串,您总是可以通过C_str((方法获得它们。

您正试图将一个字符附加到字符串文字(即"Images/image"(,这会导致访问冲突,因为它存储在只读内存中。

你应该改为:

char image[100]="Images/image";  // make it large enough to contain all the further modifications you plan to do
strcat(image,"_");

这将起作用,因为您使用的是本地缓冲区,可以自由更改。

为了避免字符串文字出现其他错误,您应该始终使用const char *来指向它们,编译器甚至不允许您尝试修改它们。

顺便说一句,既然您使用C++,就没有理由不使用C++字符串来代替char *&co.

const char* image = "Images/image"; 

更准确。您不能以任何方式附加或修改它。使用std::string。

std::string image("Images/image");
image.append(1,'_');