我有以下代码在 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;
}
谢谢您的帮助 :)