C分段故障打印缓冲区

时间:2013-07-16 19:20:45

标签: c file-io buffer

此代码编译良好并且运行完美,直到我尝试打印出缓冲区。我在网上找到了很多资源,但我无法解决我的问题!我真的很感激另一只眼睛。

这是我的代码:

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

int store_file(char* file_dir, char* buffer)
{
    FILE* file;
    long lSize;
    size_t result;
    int i;
    char* tempBuffer;

    file = fopen(file_dir, "r");
    if (file==NULL)
    {
        fputs("File error.", stderr);
        exit(1);
    }

    fseek(file, 0, SEEK_END);
    lSize = ftell(file);
    rewind(file);

    tempBuffer = (char*)malloc(sizeof(char)*lSize);
    if (tempBuffer == NULL)
    {
        fputs("Memory error.", stderr);
        exit(2);
    }

    result = fread(tempBuffer, 1, lSize, file);
    if (result != lSize)
    {
        fputs("Reading error.", stderr);
        exit(3);
    }

    buffer = tempBuffer;
    free(tempBuffer);
    fclose(file);
    return sizeof(buffer);
}

void fsa_cycle(char* file_dir)
{
    char* buffer;
    int bufferSize = store_file(file_dir, buffer);
    char n;

    // This is the line that generates the issue.
    // I have also tried printf("%s",buffer); but that also doesn't work.
    fwrite(buffer, sizeof(char), bufferSize, stdout);
}

int main(int argc, char* argv[])
{
    if(argc < 2)
    {
        printf("\nSyntax: %s <file-name>\n\n", argv[0]);
        exit(1);
    }

    fsa_cycle(argv[1]);
}

任何建议都很棒!我知道答案很愚蠢。但作为初学者,我自己很难理解。感谢您的协助。

1 个答案:

答案 0 :(得分:1)

您的问题是int store_file(char* file_dir, char* buffer)不会更改原始buffer指针,只会更改其副本。要更改buffer,您需要将指针传递给它:

int store_file(char* file_dir, char** buffer)
// whenever referring to it, use *buffer instead of buffer
// e.g. *buffer = tempBuffer;

并称之为:

int bufferSize = store_file(file_dir, &buffer);