使用strcpy()时EXC_BAD_ACCESS? [英] EXC_BAD_ACCESS when using strcpy()?

查看:165
本文介绍了使用strcpy()时EXC_BAD_ACCESS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么用以下输入调用unAnnoyWord(char *str):"hakuna matata"返回:

Why calling unAnnoyWord(char *str) with the following input: "hakuna matata" returns:

EXC_BAD_ACCESS异常(代码= 2,地址= 0x10dbc9fa8)

Exception EXC_BAD_ACCESS (code=2, address=0x10dbc9fa8)

#define RANGE 128
char annoying(char *str)
{
    char occurences[RANGE] = { 0 }; char mostAnnoying = '\0';
    do {
        if (++occurences[*str] > occurences[mostAnnoying])
            mostAnnoying = *str;
    }
    while (*str++);
    return mostAnnoying;
}


void unAnnoyWord(char *str) {
    int i=0;
    char *out = malloc(sizeof(char)*(strlen(str)+1)), mostAnnoying = annoying(str);
    do
    {
        if (*str != mostAnnoying)
        {
            out[i++] = *str;
        }
    } while (*str++);
    out[i]='\0';
    strcpy(str,out);
}

调试我的代码后,我可以确认此行引起了该问题:

After debugging my code I can confirm that this line causes the issue:

strcpy(str,out);

在main()中,我有:

in main() I have:

char* str="hakuna matata";
unAnnoyWord(str);


编辑版本:


Edited version:

int i=0,j=0;
char *out = malloc(sizeof(char)*(strlen(str)+1)), mostAnnoying = annoying(str);
do
{
    if (str[j] != mostAnnoying)
    {
        out[i++] = str[j];
    }
} while (str[j++]);
out[i]='\0';
strcpy(str,out);

推荐答案

您的问题是,在调用strcpy(str,out);时,您的str变量已被更改.

Your problem is, that when calling strcpy(str,out);, your str variable was already changed.

许多编码指南在编辑参数时都会向您发出警告.将str复制到本地变量,然后在循环中使用它:

Many coding guides give you a warning when editing a parameter. Copy str to a local variable and use this in your loop instead:

void unAnnoyWord(char *str) {
    int i=0;
    char *out = malloc(sizeof(char)*(strlen(str)+1));
    char mostAnnoying = annoying(str);
    char *str2 = str;
    do
    {
        if (*str2 != mostAnnoying)
        {
            out[i++] = *str2;
        }
        // Problem: str was modified here, now we change str2
    } while (*str2++);
    out[i]='\0';
    // => str is still the same here
    strcpy(str,out);
}

更好的编码风格是不要混合索引字符串访问(out[i])和增加字符串指针(str++).您可以删除variale i并使用out ++;-)

Better coding style is to not mix indexed string access (out[i]) and incremeingt string pointers (str++). You can remove the variale i and use out++ ;-)

这篇关于使用strcpy()时EXC_BAD_ACCESS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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