c++ - EXC_BAD_ACCESS 在用指针分配 char 时发生

标签 c++

EXC_BAD_ACCESS 发生在 *str++ = *end;。这有什么问题吗?

#include <iostream>
using namespace std;
int main() {
    char *hello = "abcdefgh";
    char c = 'c';
    char *str = hello;
    //printf("%s",str);
    char * end = str;
    char tmp;
    if (str) {
        while (*end) {
            ++end;
        }
        --end;
        while (str < end) {
            tmp = *str;
            printf("hello:%s str:%c, end:%c\n", hello, *str, *end);
            *str++ = *end;
            *end-- = tmp;

        }
    }

    return 0;
}

最佳答案

尝试更改字符串文字是未定义的行为。将您的代码更改为以下等效代码,您将看到问题:

const char *hello = "abcdefgh";
const char *str = hello;
const char * end = str;

那么你明白为什么行 *str++ = *end; 有问题了吗?您正在尝试写入 const 区域,但您不能这样做。

如果你想要一个更简单的例子:

int main()
{
  char *str = "abc";
  str[0] = 'x';
}

如果这个简单的程序在

str[0] = 'x';

行被执行。

不幸的是,字符串文字不必在 C 中声明为 const char*,而 C++ 带来了这种语法。因此,即使看起来您没有使用const,但您确实在使用。

如果您希望代码真正起作用,请声明一个可写缓冲区,即一个 array 字符:

char hello[] = "abcdefgh";
char str[100];
strcpy(str, hello);
char end[100];
strcpy(end, str);

关于c++ - EXC_BAD_ACCESS 在用指针分配 char 时发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29723371/

相关文章:

c++ - 更快的均值计算(openCV,C++)

c++ - 里面的const变量是什么?

c++ - 你能在 C++ 内联汇编中建议我更好的解决方案吗?

c++ - (2 个问题) 'class' 类型重定义(即使使用#pragma once),以及静态函数内部的静态成员对象初始化?

c++ - 如果 cpp 中的数据类型条目不正确,如何允许多个输入?

c++ - UTF-8 字符串的简单加密,结果是 NULL 终止字符串?

c++ - 链接列表中的频率

python - 您怎么知道dnn支持的图层?

c++ - 获取计算机时间c++

c++ - AfxPumpMessage() 用于什么?