为什么分段错误?

时间:2014-05-14 08:45:36

标签: segmentation-fault

我正在尝试this spoj问题。但我无法理解为什么它会在某些测试用例中给出分段错误。

#include <iostream>
#include <cstring>
#include <stdio.h>
using namespace std;
int getMin(char *txt,int n) {   
    int min = 0;
    for(int i = 0 ; i < n ; i++) {
        if(strcmp(txt+min ,txt+i) > 0)
            min = i;
    }
    return min;
}
int main() {

    char *s = new char[200005];
    scanf("%s",s);
    int n = strlen(s);
    strcat(s+n,s);
    printf("\n%d",getMin(s,n)); 
    delete[] s;
return 0;       
}

1 个答案:

答案 0 :(得分:0)

来自strcat的联机帮助页:&#34;(来源和目标)字符串可能不重叠&#34;。

那么,出了什么问题? s + n是字符串s的终止空字节。所以做这样的事情:

char *strcat(char *dest, const char *src)
{
        while (*dest != '0')
                dest++;
        while (*src != '\0')
                *dest++ = *src++;
        return dest;
}

在src中找不到空字节,因为它在我们到达时已被覆盖,因为这是您作为destimation字符串传递的地址。所以你的strcat函数会继续运行,直到它遇到访问冲突并且你的程序出现故障。

相关问题