代码不起作用。继续获得分段错误(核心转储)

时间:2016-03-19 23:17:22

标签: c

这是C函数的代码,如果字符串s1出现在字典中的字符串s2之前返回1,或者如果s2出现在s2之前则返回-1,如果它们相同则返回0。

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int strcmp_ign_case(char *s1, char *s2){
   char *s1Copy;
   char *s2Copy;
   char *s1Copy3 = s1Copy;
   char *s2Copy3 = s2Copy;
   char *s1Copy2 = s1;
   char *s2Copy2 = s2;

   while(*s1Copy2 != '\0'){
       *s1Copy3 = *s1Copy2;
       *s1Copy3 = tolower(*s1Copy3);
       s1Copy3++;
       s1Copy2++;
   }
   *s1Copy3 = '\0';

   while(*s2Copy2 != '\0'){
       *s2Copy3 = *s2Copy2;
       *s2Copy3 = tolower(*s2Copy3);
       s2Copy3++;
       s2Copy2++;
   }
   *s2Copy3 = '\0';

   while((*s1Copy != '\0') || (*s2Copy != '\0')){
       if(*s1Copy > *s2Copy){
           return 1;
       } else if(*s1Copy < *s2Copy){
           return -1;
       } else {
           s1Copy++;
           s2Copy++;
       }
   }

   if((*s1Copy == '\0') && (*s2Copy == '\0')){
       return 0;
   }
}

我不明白代码有什么问题。请帮我理解这里的错误。谢谢!

这是我用来测试它的主要内容:

void main(){
    char *a1 = "hello";
    char *a2 = "hell";
    char *a3 = "world";
    printf("strcmp_ign_case1: %d\n", strcmp_ign_case(a1,a2));
    printf("strcmp_ign_case2: %d\n", strcmp_ign_case(a1,a3));
    printf("strcmp_ign_case3: %d\n", strcmp_ign_case(a2,a3));
}

2 个答案:

答案 0 :(得分:2)

见评论:

int strcmp_ign_case(char *s1, char *s2){
   char *s1Copy;   // uninitialized pointer
   char *s2Copy;
   char *s1Copy3 = s1Copy; // copy of uninitialized pointer
   char *s2Copy3 = s2Copy;
   char *s1Copy2 = s1;
   char *s2Copy2 = s2;

   while(*s1Copy2 != '\0'){
       *s1Copy3 = *s1Copy2; // dereferenced uninitialized pointer (crash)

答案 1 :(得分:0)

感谢您的帮助。

我修正了我的错误:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int strcmp_ign_case(char *s1, char *s2){
   char *s1Copy = s1;
   char *s2Copy = s2;

   while(*s1Copy != '\0') || (*s2Copy != '\0')){
       if(tolower(*s1Copy) > tolower(*s2Copy)){
           return 1;
       } else if(tolower(*s1Copy)< tolower(*s2Copy)){
           return -1;
       } else {
           s1Copy++;
           s2Copy++;
       }
   }

   if((*s1Copy == '\0') && (*s2Copy == '\0')){
       return 0;
   }
}