2014-05-14 85 views
0

我正在嘗試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;  
} 

回答

0

strcat的手冊頁:「(源和目標)字符串可能不重疊」。

那麼,出了什麼問題? s + n是字符串s的終止空字節。所以做這樣的事情:

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

不會找到SRC空字節,因爲它已經超額我們得到它的時候寫的,因爲那是你作爲destimation字符串傳遞地址。所以你的strcat函數會一直持續下去,直到出現訪問衝突和程序段錯誤。