سؤال

I am trying this spoj problem.But I could not get why it is giving segmentation fault in some test case.

#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;       
}
هل كانت مفيدة؟

المحلول

From the manpage of strcat: "The (source and destination) strings may not overlap".

So, what is going wrong? Well s+n is the terminating null byte of string s. So doing something like this:

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

Will not find a null byte in src, because it has been over written by the time we get to it, because that is the address you passed as the destimation string. And so your strcat function keeps going until it gets an access violation and your program seg faults.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top