无法从我的 main 函数中访问使用 malloc 分配的内存

问题描述 投票:0回答:1

据我所知,在函数中使用 malloc 分配内存允许您在 main 中使用该内存,直到您手动释放它。我有一个函数可以读取 MNISTI 图像文件并以整数数组的形式为每个图像创建一个向量。这是代码:

int* readNextMNISTImage(const char* file_path) {
    static int current_image = 0;

    FILE* file = fopen(file_path, "rb");
    if (file == NULL) {
        fprintf(stderr, "Error opening file: %s\n", file_path);
        return NULL;
    }

    fseek(file, 16 + IMAGE_SIZE * current_image, SEEK_SET);

    int* vector = (int*)malloc(IMAGE_SIZE * sizeof(int));
    if (vector == NULL) {
        fprintf(stderr, "Error allocating memory for image vector.\n");
        fclose(file);
        return NULL;
    }

    for (int j = 0; j < IMAGE_SIZE; ++j) {
        uint8_t pixel;
        size_t bytesRead = fread(&pixel, sizeof(uint8_t), 1, file);
        if (bytesRead != 1) {
            fprintf(stderr, "Error reading pixel data.\n");
            free(vector);
            fclose(file);
            return NULL;
        }
        vector[j] = (int)pixel; // Store pixel value as an integer
    }
    for (int i=0;i<IMAGE_SIZE;i++)
    printf("%d ", vector[i]);
    fclose(file);
    current_image++;
    return vector;
}

如果我在这个函数中添加一个 for 循环来打印向量数组的内容,我可以看到它是按照我想要的方式创建的。字节数组,取值范围为 0 到 255。一切都很好。我在主函数中返回指向该数组的指针,并尝试以相同的方式将其打印在那里,以便我可以查看它是否可用,并且出现段错误。我想这是非常基本的东西,但我不明白为什么。这是我的主要内容:

int main() {
    char file_path[256];    
    
    printf("Enter the path to the dataset file: ");
    scanf("%s", file_path);
    
    int* vector = readNextMNISTImage(file_path);
    for (int i = 0; i < IMAGE_SIZE; i++)
    printf("%d ", vector[i]);
    free(vector);
    return 0;
}
c function pointers return malloc
1个回答
0
投票

解决了。我的 .h 文件中的函数声明中缺少一个字母......我想如果是这种情况,程序将无法编译。抱歉给大家带来麻烦了

© www.soinside.com 2019 - 2024. All rights reserved.