输入后Char指针(字符串)数组崩溃了?

时间:2014-01-16 16:21:39

标签: c arrays string gets

我想存储一个字符串数组,计算它们的长度并使用下面提到的算法以长度增加顺序(最小 - >更大)重新排列它们//
交换持有一个相对较大的字符串来替换顺序(当发现另一个分钟时)
我可以使用realloc(),但我还没考虑保护编程

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



int main()
    {
        int i,j,N;
        printf("\n Input amount of alphanumericals: ");
        scanf("%d",&N);
            {
                int min;
                char *swap=(char*)malloc(sizeof(char)*150);
                char *A[N],**temp;
                temp=A;
                for(i=0;i<N;i++){
                    printf("\nInput %d element:",i+1); 
                    fgets(temp+i,150,STDIN);
                }


    printf("\n\nData [");
    for(i=0;i<N;i++)
        printf(" %s",A[i]);
    printf(" ]\n\n");

    //Ins sort
    for(i=0;i<N;i++){
        min=i;//Assume current is min
        for(j=i+1;j<N;j++){
            //Compare assuming min with current
            if(strcmp(A[j],A[min])<0){
                min=j;
            }
            //If next is min replace in current position
        if(min!=i){
            swap=A[i];
            A[i]=A[min];
            A[min]=swap;
        }   
    }
    free(swap);
    printf("\nAfter insertion point algorithm\n");
    printf("\n\nInsertion Sorted Data [");
    for(i=0;i<N;i++)
        printf(" %s",A[i]);
    printf(" ]");
    }
    return 0;
}

2 个答案:

答案 0 :(得分:2)

您想要释放未使用malloc分配的内存:

char *A[N],**temp;
temp = A;   // A is an automatic (AKA "stack") variable; now temp points to it as well
free(temp); // Undefined behavior

在循环内部,您正在使用gets读取尚未分配的字符串:

gets(temp+i); // That's the same as gets(A[i]); Your A[i]s are unallocated.

作为旁注,您不应该使用gets,因为它是缓冲区溢出的主要来源。请改用fgets,并将stdin作为FILE*参数传递。使用scanf %20s是限制尺寸的另一种选择。

此外,由于i1转到N(包括{1}},因此此表达式在最后一次迭代时引用了A数组之后的一个元素:

gets(temp+i); // Undefined behavior when i==N

编辑:为什么下面的代码会崩溃?

for(i=0;i<N;i++){
    printf("\nInput %d element:",i+1); 
    fgets(temp+i,150,STDIN);
}

以下代码崩溃,因为您没有为各个字符串分配内存:

for(i=0;i<N;i++){
    printf("\nInput %d element:",i+1);
    temp+i = malloc(151); // No need to multiply by sizeof(char) or cast to char*
    fgets(temp+i,150,STDIN);
}

请注意,您需要为null终止符分配一个额外的char

答案 1 :(得分:0)

您没有正确使用gets:请查看其手册页[1]。此外,建议不要使用gets:更好地使用fgets

此外,gets没有为您分配字符串,因此当您传递char *指针时,指针必须指向有效的内存位置。相反,你的A[n]是一系列悬空指针。

然后,为什么free(temp)?您必须为分配了free的每个指针调用malloc:不是temp的情况。

最后,请格式化您的代码:使用indent

[1] http://linux.die.net/man/3/gets

相关问题