gpt4 book ai didi

c++ - 重构后的 EXC_BAD_ACCESS 问题

转载 作者:行者123 更新时间:2023-11-28 03:21:03 25 4
gpt4 key购买 nike

以下代码在 Marmalade 模拟器中运行(我在 OSX 上使用 x-code)

bool PictureDictionary::OnTableSelect(CTable* table, int tab){
//if something is selected, look up the item, and display it
//also change the search to the selected item
if(-1 < tab){

// if a term is selected, set the search text field to the term
CString term = m_SearchResults.GetString(tab);

if(m_currentWord != (char*)term.Get()){
m_currentWord = (char *)term.Get();
m_searchTextField->SetAttribute("text", term);

char* normalizedTerm = (char *)term.Get();
char* imagePath;
sprintf(imagePath,"images/%s.jpg", normalizedTerm);

if(m_ImageAttached){
m_Image->SetAttribute("image", (const char*)imagePath);
} else {
m_Image = CreateImage(CAttributes()
.Set("name", "picture")
.Set("x1", "0")
.Set("x2", "0")
.Set("y1", "50%")
.Set("image", (const char*)imagePath)
);
m_SearchView->AddChild(m_Image);
m_ImageAttached = true;
}
}
}
return true;
}

当我运行模拟器并从表中选择一个项目时,图像会出现,并且当我选择不同的项目时会发生变化。当我去重构时,我得到一个 EXC_BAD_ACCESS (code=1…..) 错误

bool PictureDictionary::OnTableSelect(CTable* table, int tab){
//if something is selected, look up the item, and display it
//also change the search to the selected item
if(-1 < tab){

// if a term is selected, set the search text field to the term
CString term = m_SearchResults.GetString(tab);

if(m_currentWord != (char*)term.Get()){
m_currentWord = (char *)term.Get();
m_searchTextField->SetAttribute("text", term);

char* normalizedTerm = (char *)term.Get();
char* imagePath;
sprintf(imagePath,"images/%s.jpg", normalizedTerm);

UpdatePictureView(imagePath);
}
}
return true;
}

void PictureDictionary::UpdatePictureView(char* imagePath){
if(m_ImageAttached){
m_Image->SetAttribute("image", (const char*)imagePath);
} else {
m_Image = CreateImage(CAttributes()
.Set("name", "picture")
.Set("x1", "0")
.Set("x2", "0")
.Set("y1", "50%")
.Set("image", (const char*)imagePath)
);
m_SearchView->AddChild(m_Image);
m_ImageAttached = true;
}
}

关于如何在不出现这些问题的情况下清理代码的任何建议?

编辑 RE 关于未初始化变量的注释:m_ImageAttached 在构造函数中被初始化为 false,除非我做错了什么。此外,更改条件以检查 m_Image!=NULL 是否也会引发相同的错误。

主要.cpp:

PictureDictionary pictDict(myApp, &dictionary);

PictureDictionary 的构造函数:

PictureDictionary::PictureDictionary(CAppPtr app,Dictionary::Dictionary* dictionary){
m_App = app;
m_Dictionary = dictionary;
m_currentWord = "";
m_ImageAttached = false;
}

最佳答案

imagePath 在两个片段中都是一个未初始化的指针。任何取消引用的尝试都是未定义的行为。它似乎在第一个代码段中起作用。使用数组或填充 std::string 代替:

std::string imagePath(std::string("images/") + normalizedTerm + ".jpg");

如果需要访问底层 const char*,则使用 std::string::c_str()

关于c++ - 重构后的 EXC_BAD_ACCESS 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15430393/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com