然而,我不太擅长使用C++;我的代码被编译了,但是函数使我的程序崩溃,下面是代码的简短总结;它并不完整,但是函数和调用在那里。
void rot13(char *ret, const char *in);
int main()
{
char* str;
MessageBox(NULL, _T("Test 1; Does get here!"), _T("Test 1"), MB_OK);
rot13(str, "uryyb jbeyq!"); // hello world!
/* Do stuff with char* str; */
MessageBox(NULL, _T("Test 2; Doesn't get here!"), _T("Test 2"), MB_OK);
return 0;
}
void rot13(char *ret, const char *in){
for( int i=0; i = sizeof(in); i++ ){
if(in[i] >= 'a' && in[i] <= 'm'){
// Crashes Here;
ret[i] += 13;
}
else if(in[i] > 'n' && in[i] <= 'z'){
// Possibly crashing Here too?
ret[i] -= 13;
}
else if(in[i] > 'A' && in[i] <= 'M'){
// Possibly crashing Here too?
ret[i] += 13;
}
else if(in[i] > 'N' && in[i] <= 'Z'){
// Possibly crashing Here too?
ret[i] -= 13;
}
}
}该函数到达“测试1;确实到达这里!”-但是它没有到达“测试2;没有到达这里!”
感谢您的支持。-Nick Daniels
发布于 2012-05-09 22:27:30
str未初始化,并且在rot13中被取消引用,从而导致崩溃。在传递给rot13()之前(在堆栈上或动态地)为str分配内存:
char str[1024] = ""; /* Large enough to hold string and initialised. */rot13()内部的for循环也不正确(无限循环):
for( int i=0; i = sizeof(in); i++ ){更改为:
for(size_t i = 0, len = strlen(in); i < len; i++ ){ 发布于 2012-05-09 22:32:16
你有几个问题:
str。这就是导致崩溃的原因。循环条件总是计算为true (=赋值并返回赋值,equality).sizeof(in),目的是获得输入字符串的大小,但这实际上会给出指针的大小。请改用strlen。https://stackoverflow.com/questions/10518044
复制相似问题