簡體   English   中英

在此代碼上出現分段錯誤

[英]Getting segmentation fault on this code

我已經嘗試了一段時間,以找出為什么我在此代碼上出現分段錯誤。 它應該從文件中獲取一些11位數字,找出哪些以相同的4位數字開頭並在屏幕上列出。

   #include <stdio.h>

   #include <stdlib.h>

   #include <string.h>

    #define CHOP_SIZE 5

    #define INIT_CHOP 100


    typedef enum{
        OK,
        ERROR_MEMORY,
        ERROR_NULL_POINTER,
    } state_t; 

    state_t list(FILE * file,int number){
        int *v, *aux;
        size_t used_size;
        size_t alloc_size, i;
        for(used_size=0;fscanf(file,"%d",&v[used_size])==EOF;used_size++){
            if(used_size==0){
                if((v=(int*)malloc(sizeof(int)*INIT_CHOP))==NULL)return ERROR_MEMORY;
                alloc_size=1;
            }   
            if(used_size==alloc_size){
                if((aux=(int*)realloc(v,sizeof(int)*(alloc_size+CHOP_SIZE)))==NULL){
                    free(v);
                    v=NULL;
                    return ERROR_MEMORY;
                }
                alloc_size+=CHOP_SIZE;
                v=aux;
            }
        }
        for(i=0;i<used_size;i++){
            if(v[i]/10000000==number){
                printf("%d\n",v[i]);
            }
        }
        return OK;
    }

    int main(void){
        FILE *file;
        state_t state;
        file=fopen("file1","rb");
        state=list(file, 1111);
        return EXIT_SUCCESS;
    }

您寫入未初始化指針v + used_size所尋址的位置。

 for(used_size=0;fscanf(file,"%d",&v[used_size])==EOF;used_size++){

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM