繁体   English   中英

为什么我的程序给我一个中止陷阱:6错误?

[英]Why is my program giving me an Abort Trap: 6 error?

这段代码应该对字符串数组进行排序,但是在选择排序中主循环的第二次迭代前后,它给了我一个异常终止陷阱:6错误。 我正在Mac的终端上运行它。 这是代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

int letSize = 20;
int vecSize;
char **array1;

void selectionSort (int low, int high)
{
    char *temp = malloc ((letSize + 1) * sizeof (char));
    int i = 0, j = 0;

    for (i = low; i < high - 1; i++) {
        int indexOfMin = i;
        for (j = i + 1; j < high; j++)
            if (strcmp (array1[j], array1[indexOfMin]) < 0)
                indexOfMin = j;
        //after second main loop, error occurs
        strcpy (temp, array1[i]);
        strcpy (array1[i], array1[indexOfMin]);
        strcpy (array1[indexOfMin], temp);
    }
}

int main ()
{
    int i, j;

    printf ("Enter size of items to be sorted: ");
    scanf ("%d", &vecSize);
    array1 = malloc (vecSize * sizeof (char *));
    for (i = 0; i < vecSize; i++)
        array1[i] = malloc ((letSize + 1) * sizeof (char));

    srand (time (NULL));
    for (i = 0; i < vecSize; i++) {
        for (j = 0; j <= letSize; j++) {
            if (j != letSize) {
                char randLet = 'A' + (random () % 26);
                array1[i][j] = randLet;
            } else
                array1[i][j] = '\0';
        }
    }
    selectionSort (0, vecSize);
}

这是给我麻烦的代码。 它可以毫无问题地进行编译,并且还可以从用户那里获取输入,但是在病房之后,它给了我中止陷阱的错误:6.可能是什么原因造成的? 提前致谢。

问题是您尝试在j == indexOfMin (或当j == i )时尝试进行复制,该尝试尝试使用strcpy复制重叠的内存区域(可以使用memmove ,而不是strcpy )。 man strcpy

strcpy()函数将src指向的字符串(包括终止的空字节('\\ 0'))复制到dest指向的缓冲区。 The strings may not overlap ,.....

您仅需要检查并仅在j != indexOfMin进行复制,以防止尝试在其自身上复制字符串。 例如:

void selectionSort (int low, int high)
{
    char *temp = malloc ((letSize + 1) * sizeof (char));
    int i = 0, j = 0;

    for (i = low; i < high - 1; i++) {
        int indexOfMin = i;
        for (j = i + 1; j < high; j++)
            if (strcmp (array1[j], array1[indexOfMin]) < 0)
                if (j != indexOfMin) {
                    indexOfMin = j;
                    strcpy (temp, array1[i]);
                    strcpy (array1[i], array1[indexOfMin]);
                    strcpy (array1[indexOfMin], temp);
                }
    }
    free (temp);
}

还请记住要free (temp)否则您将保证有内存泄漏。

暂无
暂无

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

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