简体   繁体   English

我正在尝试将文件读入数组并不断收到此错误

[英]I'm trying to read a file into an arrray and keep getting this error

help me please.请帮帮我。 I'm trying to read a file into an array and return the max amount of numbers in the file.我正在尝试将文件读入数组并返回文件中的最大数量。 I keep getting a segmentation fault error and I know its probably because of how I'm handling the Array but I can find the exact issue, The issue is in the function ReadFileInotArray.我不断收到分段错误错误,我知道这可能是因为我处理数组的方式,但我可以找到确切的问题,问题出在函数 ReadFileInotArray 中。 After the function is over I get the error shown below.功能结束后,我收到如下所示的错误。

#include <stdlib.h> 
#include <stdio.h> 
#include <string.h>
#include <time.h>
void PrintArray(int ArrayToPrint[], int SizeAP)
{
    int i;
    printf("{");
    for (i=0; i< SizeAP; i++)
        printf("%d,", ArrayToPrint[i]);
    printf("\b}\n");
}

void swap(int *SwapA, int *SwapB)
{
    int temp = *SwapA;
    *SwapA = *SwapB;
    *SwapB = temp;
}

int partition (int A[], int low, int high) 
{ 
    int i, j = 0;
    #if QSM
    int middle = (high+low)/2;
    swap(&A[middle], &A[high]);
    #elif QSRND
    int random = (rand() % (high-low+1)) + low;
    swap(&A[random], &A[high]);
    #endif
    int pivot = A[high];
    i= (low - 1); 
    for (j = low; j < high; j++) 
    { 
        if (A[j] < pivot) 
        { 
            i++; 
            swap(&A[i], &A[j]);
        } 
    } 
    swap(&A[i+ 1], &A[high]);
    return (i+ 1);
}

void QuickSort(int A[], int low, int high) 
{ 
    if (low < high) 
    {
       int ndx= partition(A, low, high);
       QuickSort(A, low, ndx-1); 
       QuickSort(A, ndx+ 1, high); 
    } 
}

void ReadFileIntoArray(int argc, char *argv[], int A[],int size)
{
    char line[200];
    int j=0;
    if(argv[1]==NULL) 
    {   
        printf("File must be provided on command line...exiting\n");
        exit(0);
    }
    
    FILE *fp = fopen(argv[1],"r");
    
    if(fp==NULL) 
    {
        printf("Exiting: no such file in directory\n");
        exit(0);
    }
    while(fgets(line,200,fp)!=NULL) 
    {
        size++;
    }
    fseek(fp,0,0); 
    A=malloc(sizeof(int)*size);
    while(j<size && fgets(line,200,fp)!=NULL ) 
    {
    
        A[j]=atoi(line);
        printf("%d\n",A[j]);
        j++;
    }
    printf("%d",size);
    PrintArray(A,size);

}

int main(int argc ,char *argv[]) 
{ 
    clock_t start,end;
    int i,control,count=0,size;
    int *array;
    
    if(argv[2]==NULL)
    { 
        printf("Number of runs not specified on the command line...defaluting to 10");
        control=10;
    }
    else 
        control=atoi(argv[2]);
    for(i=1; i<=control; i++)
    {
        ReadFileIntoArray(argc,argv,array,size);
        #ifdef PRINTARRAY
        PrintArray(array, size);
        #endif
        printf("ok");
        start = clock();
        QuickSort(array, 0, size-1);
        end = clock();
        printf("\nRun %d complete: %ld tics",i ,end-start);
        count+=end-start;
    
        #ifdef PRINTARRAY
        PrintArray(array,size);
        #endif
    
        free(array);
    }
    printf("\nThe average run time for %s runs is %d\n",argv[2],count/i);
    printf("\nProcessed %d records\n",size);
    return 0; 
} 

Here is the output I get when running in the VM.这是我在 VM 中运行时得到的输出。

student@maverick:/media/sf_VM_folder/CSE_3318_code@ gcc Code3_1001472179.c 
student@maverick:/media/sf_VM_folder/CSE_3318_code$ ./a.out TestFile.txt 5
472179
93424
313939
263358
154966
93659
221593
284590
439245
154572
10{472179,93424,313939,263358,154966,93659,221593,284590,439245,154572}
ok
munmap_chunk(): invalid pointer
Aborted (core dumped)

You haven't pasted complete code but I'm assuming here's what's happening.你还没有粘贴完整的代码,但我假设这是发生了什么。 You've just passed in array from main directly.您刚刚直接从 main 传入array Your modifications to A in ReadFileIntoArray() won't be reflected in main() and since you haven't even initialized array , accessing it in main() is Undefined Bevahoiour and probably a crash.您在ReadFileIntoArray()A修改不会反映在main()并且由于您甚至还没有初始化array ,因此在main()访问它是 Undefined Bevahoiour 并且可能会崩溃。 You need to pass in &array and accept an int** A in ReadFileIntoArray()您需要传入&array并在ReadFileIntoArray()接受一个int** A

PS There's bug with how you use size too since the changes made to size in ReadFileIntoArray() won't be reflected back in main() , You need to pass in &size and accept int* size in ReadFileIntoArray() . PS 您如何使用size也存在错误,因为在ReadFileIntoArray()size所做的更改不会反映在main() ,您需要传入&size并在ReadFileIntoArray()接受int* size

EDIT: You're exactly doing what I'd assumed.编辑:你正在做我假设的事情。 When you call QuickSort(array, 0, size-1);当你调用QuickSort(array, 0, size-1); , array doesn't have any values and points to some indeterminate value (or possibly NULL ). , array没有任何值并指向某个不确定的值(或可能为NULL )。

I'll share a small example to explain what's wrong.我将分享一个小例子来解释什么是错的。

void readIntoArray(int array[], int size) {
    printf("%s: Initial values %p - %d\n", __FUNCTION__, array, size);
    //code to read the vale of size from file
    size = 5;
    array = malloc(sizeof(int) * size);
    printf("%s: End values %p - %d\n", __FUNCTION__, array, size);
}

int main() {
    int * array;
    int size;
    printf("%s: Initial values %p - %d\n", __FUNCTION__, array, size);
    readIntoArray(array, size);
    printf("%s: End values %p - %d\n", __FUNCTION__, array, size);
}

This, on some compiler , could yield output like:在某些编译器上,这可能会产生如下输出:

main: Initial values (nil) - 32766
readIntoArray: Initial values (nil) - 32766
readIntoArray: End values 0x2435020 - 5
main: End values (nil) - 32766

Note what's happening here.注意这里发生了什么。 Even though you changed array inside readIntoArray() to point to some malloc 'd memory, that doesn't reflect back in the main() .即使您将readIntoArray() array更改为指向某些malloc的内存,这也不会反映在main() Same is the case with size . size也是如此。 This is a very basic concept in C wherein arguments are passed to functions by value and are copied.这是 C 中一个非常基本的概念,其中参数按值传递给函数并被复制。 To have the changes done in readIntoArray , you need to pass them by reference by passing in their addresses using the & operator, something like this :要在readIntoArray完成更改,您需要通过使用&运算符传递它们的地址来通过引用传递它们,如下所示

void readIntoArray(int **array, int* size) {
    printf("%s: Initial values %p - %d\n", __FUNCTION__, *array, *size);
    //code to read the vale of size from file
    *size = 5;
    *array = malloc(sizeof(int) * *size);
    printf("%s: End values %p - %d\n", __FUNCTION__, *array, *size);
}

int main() {
    int * array;
    int size;
    printf("%s: Initial values %p - %d\n", __FUNCTION__, array, size);
    readIntoArray(&array, &size);
    printf("%s: End values %p - %d\n", __FUNCTION__, array, size);
}

which yields the output:产生输出:

main: Initial values (nil) - 32766
readIntoArray: Initial values (nil) - 32766
readIntoArray: End values 0x1217020 - 5
main: End values 0x1217020 - 5

PS These are just examples and when dealing with pointers, it's always best to check for them being NULL before dereferencing them like *array , *size . PS 这些只是示例,在处理指针时,最好先检查它们是否为NULL然后再像*array*size那样取消引用它们。

暂无
暂无

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

相关问题 我正在尝试为分配创建代码,但我不断收到我无法弄清楚的 memory 错误 - I'm trying to create code for an assignment and I keep getting a memory error that I can't figure out 我正在尝试在文件中写入特定数量的行,但我不断收到一个空行作为第一行 - I'm trying to write a specific number of lines in a file but I keep getting a blank line as the first one 我正在尝试使用条件表达式?:在 C 中,但不断出现错误 - I'm trying to use conditional expression ?: in C but keep getting errors 尝试一个功能,但我不断收到错误 - Trying a function, but I keep getting an error 尝试使用双指针结构读取 csv 文件并打印出条目,但我在 C 中收到“大小为 8 的无效读取” - Trying to use a double pointer struct to read a csv file and print off the entries but I'm getting "Invalid read of size 8" in C 我不断收到信号:尝试执行文件 I/O 时出现分段错误(核心转储)错误 - i keep getting a signal: segmentation fault (core dumped) error while trying to do file I/O C-为什么我在尝试读取包含反斜杠的字符时遇到段错误? - C - Why I'm getting a segfault when I'm trying to read a char what contains backslash? 我正在尝试从文件中仅读取前3个字符-c - I'm trying to read only the first 3 chars from a file - c 从文件中读取文本,将行存储在错误中 - Read text from file, store lines in arrray 嘿,我正在尝试使用 C 中的链表尝试所有可能性,但是当我尝试删除第一项(弹出)时,我一直收到错误消息 - Hey! I'm trying to try out all of the possibilities with linked lists in C, but when I try to remove the first item (pop), I keep getting an error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM