简体   繁体   English

Xcode Exc_BAD_ACCESS

[英]Xcode Exc_BAD_ACCESS

so this code is giving me the Exc_bad_access_code(2) error and i have no idea why.所以这段代码给了我Exc_bad_access_code(2)错误,我不知道为什么。 I think the problem is with the parameters but im not sure, any thoughts?我认为问题出在参数上,但我不确定,有什么想法吗?

#include <stdio.h>

void swap(char *x, char *y);


/* Function to swap values at two pointers */
void swap(char *x, char *y)
{
    char temp;
    temp = *x;
    *x = *y;
    *y = temp;
}

int main(int argc, const char * argv[]) {
    // insert code here...

    char *a = "ASD123";
    swap (a+1 , a+2);

    return 0;
}

You need to post the complete crash log to be sure, but it's probably that you are attempting to manipulate a string constant:您需要发布完整的崩溃日志以确保,但您可能正在尝试操作字符串常量:

char *a = "ASD123";
swap (a+1 , a+2);

which probably lives in read-only memory.它可能存在于只读内存中。

Try:尝试:

char a[12];
strcpy(a, "ASD123");
swap (a+1 , a+2);

or:或者:

char a[] = "ASD123";
swap (a+1 , a+2);

That will copy the string onto the stack, where it may be modified without issue.这会将字符串复制到堆栈中,在那里可以毫无问题地对其进行修改。 You could also use strdup() to copy the string onto the heap (don't forget to call free() to release the allocated memory).您还可以使用strdup()将字符串复制到堆上(不要忘记调用free()来释放分配的内存)。

You need to initialize a correctly.您需要正确初始化a Something like char a[7] = "ASD123";类似于char a[7] = "ASD123";

char* a only creates a pointer-to-char , it does not allocate enough memory to store the characters. char* a只创建一个pointer-to-charpointer-to-char ,它没有分配足够的内存来存储字符。

You are trying to modify a string literal.您正在尝试修改字符串文字。

Change改变

char *a = "ASD123";

to

char a[] = "ASD123";

and your program will work.你的程序会起作用。

In the first case a is simply a pointer pointing to a string literal which is in a write protected part of the memory on most platforms, hence the crash because you try to write info write protected memory.在第一种情况下, a只是一个指向字符串文字的指针,该字符串文字位于大多数平台上内存的写保护部分,因此崩溃是因为您尝试写入信息写保护内存。

In the second case a is a char array of length 7 which is initialized with "ASD123" (6 chars for the string and one char for the terminating zero).在第二种情况下, a是一个长度为 7 的字符数组,它用“ASD123”初始化(6 个字符用于字符串,一个字符用于终止零)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM