简体   繁体   English

尝试复制字符串元素(C)时出现分段错误

[英]Segmentation fault when trying to copy elements of a string (C)

I am trying to work on a problem for school which requires me to reverse a string in place (among other things..). 我正在尝试解决一个学校上的问题,该问题要求我在适当的地方扭转弦(等等)。 I have been struggling with this for awhile and am out of ideas.. here is my code: 我已经为此苦苦挣扎了一段时间,没有想法..这是我的代码:

void strRev(char*s)
{
    int i = 0;
    int length = strlen(s);
    char*rev = (char*)malloc((length+1)*sizeof(char));

    strcpy(rev,s);

    for(i;i<length;i++)
        s[i] = rev[length - 1 - i];

    printf("%s    %s",rev,s);
}

int main()
{
    char * test = "hello";
    strRev(test);
}

when I step through in Visual Studio, it hangs when it reaches the line inside the for loop. 当我在Visual Studio中逐步执行时,到达for循环内的行时它挂起。 Unix gives me a segmentation fault. Unix给我一个分割错误。 I know this must be something simple I'm missing, but I'm out of ideas and none of the answers online are helping.. And I'm running out of time.. Someone please enlighten me, what am I doing wrong? 我知道这一定是简单的事情,我很想念,但是我没有想法,网上的答案也无济于事。而且我的时间不多了。请有人启发我,我在做什么错了?

Well, your code doesn't do it in place (else you wouldn't use malloc, also why are you using sizeof(char)?). 好吧,您的代码没有就位(否则您将不会使用malloc,为什么还要使用sizeof(char)?)。

Try this: 尝试这个:

void strRev(char*s)
{
    int i, len;
    char tmp;
    len = strlen(s);
    for(i = 0; i < (len >> 1); ++i)
    {
       tmp = s[len - 1 - i];
       s[len - 1 - i] = s[i];
       s[i] = tmp;
    }
}

And then modify you main() as the comments suggest. 然后根据注释建议修改main()。

test points to statically allocated buffer which must not be modified. test指向不可修改的静态分配缓冲区。 And you do modify it by assigning s[i]=rev[...] . 然后通过分配s[i]=rev[...] This causes segfault. 这会导致段错误。

I think you wanted to write rev[i]=s[...] . 我认为您想写rev[i]=s[...]

If you need to do it in place then allocate memory for "hello" dynamically ( strdup ) or on stack. 如果需要就地执行操作,则可以动态地为"hello"strdup )或在堆栈上分配内存。

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

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