[英]Why does MFC C++ CString(const char*) completely changing const char* value?
[英]const char * changing value during loop
我有一个通过const char *
迭代的函数,并使用该字符将对象添加到std::map
实例(如果它是一系列公认的字符之一)。
#define CHARSEQ const char*
void compile(CHARSEQ s) throw (BFCompilationError)
{
std::cout << "@Receive call " << s << std::endl;
for(int i = 0; s[i] != '\0'; i++)
{
if (std::string("<>-+.,[]").find_first_of(s[i]) == std::string::npos)
{
throw BFCompilationError("Unknown operator",*s,i);
}
std::cout << "@Compiling: " << s[i] << std::endl;
std::cout << "@address s " << (void*)s << std::endl;
std::cout << "@var s " << s << std::endl;
controlstack.top().push_back(opmap[s[i]]);
}
}
传递的字符序列为"++++++++++."
对于前三个迭代,打印语句显示预期的值“ +”,“ +”和“ +”,而s
的值继续为“ +++++++++++”。 但是,在第四次迭代中, s
变得混乱,产生诸如'Ð'
, 'öê'
, 'cR '
, 'œk'
类的奇怪值以及许多其他字符序列。 如果删除引发异常的行并允许循环继续,则s
的值不会再次更改。
其他函数可以访问s
但是由于这不是多线程程序,所以我看不出为什么会如此。 我对s
为什么在变化并不感到困惑,但是为什么它仅在第四次迭代中发生变化。
我搜索了SO,似乎唯一与此相关的帖子是此帖子,但它仍然无法回答我的问题。 (研究一直很困难,因为搜索“ const char *不断变化的价值”或类似的术语仅仅涉及数百篇关于const的部分的帖子 )。
最后,我知道我可能应该使用std::string
,如果没有答案,我会使用它,但是我仍然想了解这种行为。
编辑:
这是调用此函数的代码。
CHARSEQ text = load(s);
std::cout << "@Receive load " << text << std::endl;
try
{
compile(text);
}
catch(BFCompilationError& err)
{
std::cerr << "\nError in bf code: caught BFCompilationError @" << err.getIndex() << " in file " << s << ":\n";
std::cerr << text << '\n';
for(int i = 0; i < err.getIndex(); i++)
{
std::cerr << " ";
}
std::cerr << "^\n";
std::cerr << err.what() << err.getProblemChar() << std::endl;
return 1;
}
load
在哪里:
CHARSEQ load(CHARSEQ fname)
{
std::ifstream infile (fname);
std::string data(""), line;
if (infile.is_open())
{
while(infile.good())
{
std::getline(infile,line);
std::cout << "@loading: "<< line << '\n';
data += line;
}
infile.close();
}
else
{
std::cerr << "Error: unable to open file: " << fname << std::endl;
}
return std::trim(data).c_str();
}
并且文件fname
是++++++++++.
展开,使得每行只有一个字符。
编辑2:
这是控制台输出的示例:
@loading: +
@loading: +
@loading: +
@loading: +
@loading: +
@loading: +
@loading: +
@loading: +
@loading: +
@loading: +
@loading: .
@Receive load ++++++++++.
@Receive call ++++++++++.
@Compiling: +
@address s 0x7513e4
@var s ++++++++++.
@Compiling: +
@address s 0x7513e4
@var s ++++++++++.
@Compiling: +
@address s 0x7513e4
@var s ++++++++++.
@Compiling:
@address s 0x7513e4
@var s ßu
Error in bf code: caught BFCompilationError @4 in file bf_src/Hello.txt:
ßu
^
Unknown operatorß
您的load
功能有缺陷。 c_str()
返回的const char*
指针仅在基础std::string
对象存在之前有效。 但是data
是load
的局部变量,返回后将被清除。 它的缓冲区不会被零覆盖,而是保留为空闲内存。 因此,在返回后立即打印出该值很可能会起作用,但是您的程序可能会将新值放在该值中,并且指针所指向的值将更改。
我建议使用std::string
作为load的返回值来解决。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.