无法理解错误是否存在

时间:2017-11-05 20:27:44

标签: c arrays loops pointers

错误:

temp:-1: 6
p[0]: 6
loop:p[0]: 6
temp:0: 5
p[1]: 5
loop:p[1]: 5
temp:1: 4
p[2]: 4
loop:p[2]: 4
temp:2: 7
p[3]: 7
loop:p[3]: 7
temp:3: 9
p[4]: 9
loop:p[4]: 9
temp:4: 8
p[5]: 8
loop:p[5]: 8
temp:5: 4
temp:5: 9
temp:5: 0
p[6]: 0
loop:p[6]: 0
temp:6: 1
p[7]: 1
loop:p[7]: 1
temp:7: 2
p[8]: 2
loop:p[8]: 2
temp:8: 3
p[9]: 3
loop:p[9]: 3
temp:9: 4
temp:9: 1
temp:9: 12
increasing size 0: 6
increasing size 1: 5
increasing size 2: 4
increasing size 3: 7
increasing size 4: 9
increasing size 5: 8
increasing size 6: 0
increasing size 7: 1
increasing size 8: 2
increasing size 9: 3
a.out(58583,0x7fffb423c3c0) malloc: *** error for object 0x7fff53e9fb00: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6

我无法理解这一点。

以下是我正在运行的代码。谢谢。

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

int insert_in(int* p,int index, int* size, int item);
void swap(int* a, int* b);
void bubble_sort(int a[], int size);

int main( int argc, char* argv[]){

    int size=10;
    int index=-1;
    int p[size];
    int temp;
    int i;
    int duplicate=0;

    scanf("%d",&temp);
    //insert_in(p,index,&size,temp);
    printf("temp:%d: %d\n",index,temp);
    while(temp!=-1){
        duplicate=0;
        for(i=0;i<=index;i++){

            if(p[i]==temp){
                duplicate=1;
                break;
            }

        }

        if(duplicate!=1){
            index++;
            insert_in(p,index,&size,temp);
            printf("loop:p[%d]: %d\n",index,p[index]);
        }

        scanf("%d",&temp);
        printf("temp:%d: %d\n",index,temp);
    }

    for (i = 0; i <= index; i++) {

        printf("before p[%d]: %d\n",i, p[i]);
    }

    bubble_sort(p,index+1);

    for (i = 0; i <= index; i++) {
        printf("%d\n", p[i]);
    }
    return 0;

}

void bubble_sort(int a[], int size) {
    int n;
    int i;
    for (n = 0; n < size - 1; n++) {
        for (i = 0; i < size - 1; i++) {
            if (a[i] > a[i + 1]) {
                swap(&a[i], &a[i + 1]); 
            }
        }
    }

}

void swap(int* a, int* b) {
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
}

int insert_in(int* p,int index, int* size, int item){
    int* temp=NULL;
    int i=0;
    if(index>=(*size)){

        temp=(int*)malloc(sizeof(int)*(*size)*2);
        if(temp==NULL){
            printf("unable to allocate memory");
            return 0;
        }

        for( i=0;i<(*size);i++){

            temp[i]=p[i];
            printf("increasing size %d: %d\n",i,p[i]);

        }
        free(p);
        p=temp;
        (*size)*=2;
        printf("size %d: %d\n",i,*size);
    }

    p[index]=item;
    printf("p[%d]: %d\n",index,p[index]);
    return 1;
}

0 个答案:

没有答案