分段故障:有时为11 C.

时间:2017-10-15 18:44:49

标签: c eclipse macos segmentation-fault

我试图在我的Mac上运行C程序,要求用户输入一组名称。然后程序对所有名称进行排序和大写,并将它们打印为大写和排序。然后,它允许用户搜索名称。但是,大多数时候(但不是每次)我尝试运行代码它返回一个分段错误:11错误。我的猜测是这个问题与fgets或我的阵列有关,但我真的不知道。

这是我的代码:

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

#define SIZE 50
#define LENGTH 50
#define TRUE 1
#define FALSE 0

void printList(char names[SIZE][LENGTH], int length);
void toUpperCase(char names[SIZE][LENGTH], int length);
void sort(char names[SIZE][LENGTH], int length);
void startSearch(char names[SIZE][LENGTH], int length);
int binSearch(char names[SIZE][LENGTH], int l, int r, char x[LENGTH]);


int main(void){
    char names[SIZE][LENGTH]; //stores the list of names
    printf("Enter student names (q to stop)...\n");

    int i = 0;
    do {
        printf("Student name #%d: ", i);
        fgets(names[i], LENGTH, stdin);     //fill the list of names
        int len = strlen(names[i])-1;       //fgets includes \n character
        if(names[i][len] == '\n')           //if the last character is \n
            names[i][len] = '\0';           //change it to \0
        if(strcmp(names[i], "") == 0)
            printf("Invalid input: Type a name\n"); 
        else
            i++;
    }
    while(strcmp(names[i-1],"q")!=0 && i<SIZE); //Stop collecting names after input "q" 
                                                //or if the names array is full

    int length = i-1; //# of names in the names array

    sort(names, length);
    toUpperCase(names, length);
    printList(names, length);
    startSearch(names, length);


    printf("Done!\n");
    return 0;
}

//Converts all the names in the names array to upper case
void toUpperCase(char names[SIZE][LENGTH], int length){
    for(int i = 0; i < length; i++){
        for(int j = 0; names[i][j]!='\n'; j++){
            if(islower(names[i][j]))
                names[i][j] = toupper(names[i][j]);
        }
    }
}

//sorts the names in the names array (bubble sort)
void sort(char names[SIZE][LENGTH], int length){
   int i, j;
   char temp[LENGTH];
   for (i = 0; i < length-1; i++)
       for (j = 0; j < length-i-1; j++)
           if (strcmp(names[j],names[j+1])>0){
                   strcpy(temp, names[j]);
                   strcpy(names[j], names[j+1]);
                   strcpy(names[j+1], temp);

           }
}

//prints the names in the names array
void printList(char names[SIZE][LENGTH], int length){
    printf("Student list: [\n");
    for(int i = 0; i < length; i++)
        if(i == length-1)
            printf("\t%s\n", names[i]);
        else
            printf("\t%s,\n", names[i]);
    printf("]\n");
}

//The first method for searching the list
void startSearch(char names[SIZE][LENGTH], int length){
    char search[LENGTH];
    while(strcmp(search, "q")!=0){
        printf("Enter a name to search (q to exit): "); 
        fgets(search, LENGTH, stdin); //gets the name to search
        int len = strlen(search)-1;
        if(search[len] == '\n')
            search[len] = '\0';
        if(strcmp(search, "q") == 0)     //if entered value is q
            break;                       //break out of the loop
        //Since the list is all upper case change the search value to upper case
        for(int j = 0; search[j]!='\n'; j++){
            if(islower(search[j]))
                search[j] = toupper(search[j]);  
        }

        printf("Searching for %s ...\n", search);
        // if binSearch returns true then the item is in the list
        if(binSearch(names, 0, length-1, search) == TRUE) 
            printf("%s is in the list!\n", search); /
        else
            printf("%s is NOT in the list!\n", search);
    }
}

//binary search for the names array
int binSearch(char names[SIZE][LENGTH], int l, int r, char x[LENGTH]){
    while (l <= r)
    {
    int m = l + (r-l)/2;
    if(strcmp(names[m], x) == 0)
        return TRUE;
    if(strcmp(names[m], x) < 0)
        l = m + 1;
    else
        r = m - 1;
    }
    return FALSE;
}

1 个答案:

答案 0 :(得分:2)

我假设您正在使用SIZE和LENGTH的固定数组进行学习。对于与字符串相关的实际工作,您最好注意kpra的建议并使用更复杂但更强大的指针(分配它们并根据需要解除分配)。

在你的阅读循环中,你会杀掉所有的&#34; \ n&#34;用零替换它们。

然而,在您的toUppercase()代码中,您需要寻找&#34; \ n&#34;而不是0x0。这可能会破坏缓冲区:

//Converts all the names in the names array to upper case
void toUpperCase(char names[SIZE][LENGTH], int length){
    for(int i = 0; i < length; i++){
        for(int j = 0; names[i][j]!='\n'; j++){
            // what happens here if \n is not found and j exceeds SIZE?
            if(islower(names[i][j]))
                names[i][j] = toupper(names[i][j]);
        }
    }
}

您可以用0x0替换\ n,但我认为更安全的循环是:

     for(int j = 0; j < SIZE; j++) {
        if (yourstring[j] == 0) {
            break;
        }

通过这种方式,您确保永远不会超过SIZE,如果找到字符串结尾,则无论如何都会结束循环。请注意,这个&#39; \ n&#39;比较也用于搜索循环。