首页 文章

关于fscanf的Segfault

提问于
浏览
-2

filenamelists是一个带有两个文件指针的结构 . merge合并这两个文件管理器 . 我一时间遇到段错误(fscanf(filenamelist [0] .file1,“%d”,&chd)!= EOF) . 我认为这是因为我没有正确实现pthread . 我一直试图永远调试,所以任何帮助将不胜感激 . tempf是mergesorted数组的文件ptr . 它在合并函数本身中被重新组合 .

for(i=0; i<size; i++)
{
    if(argc==1)
    {
        char* tedious2 = (char*) malloc((strlen(argv[i+1]+7))*sizeof(char));
        strcpy(tedious2,argv[i+1]);
        filenamelist[i].file1 = fopen(strcat(tedious2,".sorted"),"r");
        filenamelist[i].file2 = NULL;
        filenamelist[i].alone = 1;
        free(tedious2);
        break;
    }
    else if(size-1 ==i && size%2 != 0)
    {
        char* tedious1 = (char*) malloc((strlen(argv[i+1]+7))*sizeof(char));
        strcpy(tedious1,argv[i+1]);
        filenamelist[i].file1 = fopen(strcat(tedious1,".sorted"),"r");
        filenamelist[i].file2 = NULL;
        filenamelist[i].alone = 1;
        free(tedious1);
    }
    else
    {
        char* tedious3 = (char*) malloc((strlen(argv[i+1]+7))*sizeof(char));
        strcpy(tedious3,argv[i+1]);
        char* tedious4 = (char*) malloc((strlen(argv[i+2]+7))*sizeof(char));
        strcpy(tedious4,argv[i+2]);
        filenamelist[i].file1 = fopen(strcat(tedious3,".sorted"),"r");
        filenamelist[i].file2 = fopen(strcat(tedious4,".sorted"),"r");
        filenamelist[i].alone = 0;
        free(tedious3);
        free(tedious4);
    }
}

// pthread_t * threadid2; // threadid2 =(pthread_t )malloc(sizeof(pthread_t)(2 * argc));

while(size>=0)
{

    i = 0;
    pthread_t* threadid2;
    threadid2 = (pthread_t*) malloc(sizeof(pthread_t)*size);
    for ( ; i<size;i++ )
    {
            pthread_create(&threadid2[i], NULL, merge, &filenamelist[i]);
    }
    i = 0;
    for ( ; i<size; i++)
    {
            pthread_join(threadid2[i], tempf);
        if (i%2 == 0)
        {
            filenamelist[i/2].file1 = tempf;
        }
        else
        {
            filenamelist[i/2].file2 = tempf;
        }

    }
        zit=0;
        truth = 0;
        while(zit<z)
        {
            if(inputFiles[zit] == tempf)
                truth = 1;
            zit++;
        }
        if(truth != 1)
        {  
            inputFiles[z] = tempf;
            z++;
        }
    if(size==1)
    size = 0;
    else if (size % 2 == 0) 
    size = size/2;
    else
    size = (size/2)+1;
    free(threadid2);

}

int chd = 0;
// if(0!=feof(tempf))
//   rewind(tempf);
//rewind(filenamelist[0]->file1);
int finish = 0;
//printf("file 1:%p",tempf);

while(fscanf(filenamelist[0].file1, "%d", &chd) != EOF) 
    finish++;
rewind(filenamelist[0].file1);

int* finarr = (int*) malloc(finish*sizeof(int));

int xx =0;

for(;fscanf(filenamelist[0].file1, "%d", &chd) != EOF; xx++)
    finarr[xx] = chd;

tempf在func的开头声明为FILE * tempf;

1 回答

  • 1
    char* tedious2 = (char*) malloc((strlen(argv[i+1]+7))*sizeof(char));
    

    这样做:

    char *tedious2 = malloc( strlen(argv[i+1]) + strlen(".sorted") + 1 );
    

相关问题