访问冲突写入位置? [英] Access violation writing location?

查看:260
本文介绍了访问冲突写入位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个函数来反转一个字符串,但我有这样的异常,当我做:* str ++ = * end;谁知道什么是什么原因?提前致谢。

  void reverse(char * str)
{
char * end = str;
char temp;
if(str)
{
while(* end)
{
end ++;
}
end--;

while(str {
temp = * str;
* str ++ = * end;
* end - = temp;
}
}
}


解决方案>

机会是,你使用字符串文字调用函数:

  reverse(ablewasiereisawelba); 

您不能修改字符串文字而不调用未定义的行为,崩溃是对尝试的有效响应修改字符串文字。请确保您传递非常量数组:

  char palindrome [] =ablewasiereisawelba 
reverse(palindrome);

C ++ 2011标准ISO / IEC 14882:2011说:


2.14.5字符串文字[lex.string]



¶12尝试修改字符串文字是未定义的。


通常,字符串文字放置在只读内存中,尝试修改一个字符串会导致崩溃。这当然是对调用未定义行为的完全合理的响应。


I am trying to write a function to reverse a string, but I got such exception when I am doing: *str++ = *end; anyone who knows what's the reason? Thanks in advance.

void reverse(char* str)
 {
    char *end = str;
    char temp;
    if(str)
    {
      while(*end)
       {
     end++;
       }
    end--;

    while(str<end)
    {
       temp = *str;
       *str++ = *end;
       *end--=temp;
    }
   }
 }

解决方案

Chances are, you called the function with a string literal:

 reverse("ablewasiereisawelba");

You can't modify string literals without invoking undefined behaviour, and crash is a valid response to an attempt to modify a string literal. Make sure you pass a non-constant array instead:

 char palindrome[] = "ablewasiereisawelba";
 reverse(palindrome);

The C++ 2011 standard, ISO/IEC 14882:2011 says:

2.14.5 String literal [lex.string]

¶12 The effect of attempting to modify a string literal is undefined.

Commonly, string literals are placed in readonly memory, and an attempt to modify one leads to a 'crash'. That is certainly a perfectly legitimate response to invoking undefined behaviour.

这篇关于访问冲突写入位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆