1

我有以下代码在 ubuntu linux 中按预期打印,但在 windows 中的 cygwin 中不打印任何内容。但是,如果我摆脱了 is_rotation 函数中的 free(t) ,那么它可以正常工作。我想知道我是在做不好的内存管理还是 cygwin 问题。为什么会这样。以及任何其他改进内存管理的建议。

这是代码:

/**
* sub is a substring of str or not
**/
int is_substring(const char* str,const char* sub){
    const char* s1=str;
    const char*  s2=sub;
    int count=0;
    while(1){       
        if(*s2=='\0') return 1;
        else if(*s1=='\0') return 0;
        else if(*s1==*s2){
            count++;
            s2++;
        }   
        else{
            if(count!=0){
                s1-=count;
                count=0;
                s2=sub;
            }
        }
        s1++;
    }
    return 0;
}
/**
* s1 and s2 are rotations of eachother or not, given only the is_substring function.
**/
int is_rotation(const char* s1,const char* s2){
    int l1=strlen(s1);
    if(l1!=strlen(s2)) return 0;
    char* t=malloc(2*l1*sizeof(char));
    strcat(t,s1);
    strcat(t,s1);
    int r=is_substring(t,s2);
    free(t);
    return r;
}

/**
* USAGE: ./a.out string1 string2
**/
int main(int argc, char *argv[]){
    if(argc<3) return 1;
    printf("is_substring=%d",is_substring(argv[1],argv[2]));
    printf("\nis_rotation=%d",is_rotation(argv[1],argv[2]));
    return 0;
}

谢谢您的帮助 :)

4

2 回答 2

4

问题出在第一次strcat()通话中。您应该将其替换为 a strcpy()

int is_rotation(const char* s1,const char* s2){
    int l1=strlen(s1);
    if(l1!=strlen(s2)) return 0;
    char* t=malloc(2*l1*sizeof(char) + 1);
    strcpy(t,s1); // initialize with strcpy() so we have a null in the string
    strcat(t,s1);
    int r=is_substring(t,s2);
    free(t);
    return r;
}

请注意,malloc()它不会初始化它正常分配的缓冲区。也许 ubuntu 上的那个可以,但不能保证。在 cygwin 中,缓冲区未初始化,因此在strcat()复制字符串之前正在寻找空的内存......这很可能超过了分配的缓冲区的末尾。

此外,您必须在缓冲区中添加一个额外的字符来保存最终字符串的空终止符......它是l1空终止符 + 1长度的 2 倍

于 2013-04-25T22:56:23.940 回答
1

这是一个杀死你的堆栈的错误:

char* t=malloc(2*l1*sizeof(char));
strcat(t,s1);
strcat(t,s1);

第一个strcat将字符添加到某处......因为您正在使用缓冲区malloc的内容是未知的。t此外,您还需要一个字节为零。

char* t=malloc(2*l1+1); // (2*l1+1)*sizeof(char)
strcpy(t,s1);
strcat(t,s1);
于 2013-04-25T22:56:48.483 回答