在 while 循环外无法访问 Malloc 内存

Malloc memory not accessible outside while loop

我正在尝试编写一个包装器以从文件中获取一些预定义的标准输入。如果开头有“#”,程序应该跳过一行,否则将除前 2 个元素之外的所有元素存储在名为 factorList 的数组中。 我正在使用 malloc 为这个指针动态分配内存。 然后我试图在我声明它的 while 循环之外访问这个数组,但是它导致了一个错误。

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

int main(int argc, char * argv[])
{
    int degree  = 100;
    int tempDegree;
    int num;
    int * factorList;
    FILE * primeFile = fopen(argv[1],"r");
    if(!primeFile)
    {
        printf("Could not open file containing prime table\n");
    }
    char store[100] = {0};
    char lineCheck = ' ';
    int primeCheck = fscanf(primeFile, "%s", store);

    while(primeCheck != EOF)
    {
        if(strcmp("#",store) == 0)
        {
            printf("Mark1\n");
            // Clearing Store array
            memset(store, 0 , sizeof(store));
            // Skip this line
            while((lineCheck != '\n') && (primeCheck != EOF))
            {
                primeCheck = fscanf(primeFile, "%c", &lineCheck);
            }

            lineCheck = ' ';
            // Reading the start of the next line
            if(primeCheck != EOF)
            {
                primeCheck = fscanf(primeFile, "%s", store);
            }
        }
        else
        {
            tempDegree = atoi(store);
            if(tempDegree == degree)
            {
                printf("Mark2\n");
                // This is the list of primes
                primeCheck = fscanf(primeFile, "%d", &num);
                factorList = malloc(sizeof(int)*num);
                int i;
                for(i=0;i < num; i++)
                {
                    primeCheck = fscanf(primeFile, "%d", &factorList[i]);
                    printf("%d",factorList[i]);
                }
                break;
            }
            else
            {    
                printf("Mark3\n");
                // Clearing Store array
                memset(store, 0 , sizeof(store));
                // Skip this line
                while((lineCheck != '\n') && (primeCheck != EOF))
                {
                    primeCheck = fscanf(primeFile, "%c", &lineCheck);
                }
                lineCheck = ' ';
                // Reading the start of the next line
                if(primeCheck != EOF)
                {
                    primeCheck = fscanf(primeFile, "%s", store);
                }
            }
        }

        // Testing Access to factorList , getting error here.
        int i = factorList[0];
    }
    return 0;
}

行:

    // Testing Access to factorList , getting error here.
    int i = factorList[0];

不在 while 循环之外。它位于循环的底部,因此将在循环的每次迭代中执行一次。

循环内部是一个分支。分支的 'true' 部分,如果读取仅包含单个 '#' 的行,则不会向 factorList 分配任何内容。因此,如果在循环的第一次迭代期间遇到“#”,程序可能会崩溃,因为您正在取消引用尚未为其分配值的指针,从而调用未定义的行为。

假树枝里面还有一个树枝。该分支的 false 部分也没有为 factorList 分配任何内容,因此如果 tempDegree == degree 在第一次迭代中不为真,也会发生同样的事情。

还有很多其他需要改进的地方,我会密切关注对您问题的一些评论。