简体   繁体   English

代码不起作用。 不断出现分段错误(核心转储)

[英]Code doesn't work. Keep getting segmentation fault (core dumped)

This is the code for a C function that returns 1 if string s1 appears before string s2 in a dictionary or returns -1 if s2 appears before s2 or returns 0 if they are the same.这是 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;
   }
}

I don't understand what is wrong with the code.我不明白代码有什么问题。 Please help me understand the error here.请帮助我理解这里的错误。 Thanks!谢谢!

This is the main that I am using to test it:这是我用来测试它的主要内容:

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));
}

See comments:看评论:

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)

Thanks for your help guys.谢谢你们的帮助。

I fixed my error like this:我像这样修复了我的错误:

#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;
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM