2

I Initiate my string and call my function like this:

int main() {
...
char *fileBuffer;
readFileToBuffer("/tmp/file.txt", &fileBuffer);
...
}

The purpose of this function is to get the contents of file.txt and put it into the fileBuffer variable. Because the content of file.txt is dynamic, I allocate the memory for fileBuffer dynamically in the readFileToBuffer() function like so:

void readFileToBuffer(char *filePath, char **fileBuffer) {
...
FILE *reqFile = fopen(filePath, "r");

fseek(reqFile, 0, SEEK_END);
long fileSize = ftell(reqFile);

fseek(reqFile, 0, SEEK_SET);

*fileBuffer = malloc(fileSize + 1);

fread(fileBuffer, fileSize, 1, reqFile);
fclose(reqFile);
...
}

This is causing a segmentation fault. I've googled around and this seems to be the correct way when allocating memory inside of a function.

Any idea why this is happening?

2
  • use valgrind and gdb, and post your debug information Commented May 21, 2015 at 10:52
  • 4
    Take a look at that fread call again. Commented May 21, 2015 at 10:52

1 Answer 1

7

In your readFileToBuffer() code, fileBuffer is of type char ** and your function is called as readFileToBuffer("/tmp/file.txt", &fileBuffer);

Then you have rightly allocated memory to *fileBuffer in readFileToBuffer() [so that is gets reflected to the fileBuffer in main()]. So, you need to pass *fileBuffer to fread() to read the contents of the files into the memory pointed by *fileBuffer.

You need to change.

fread(fileBuffer, fileSize, 1, reqFile);

to

fread(*fileBuffer, fileSize, 1, reqFile);  // notice the *

That said,

  1. Always check the return value of malloc() for success.
  2. The recommended signature for main() is int main(void).
Sign up to request clarification or add additional context in comments.

2 Comments

Nitpicking: The need to pass *fileBuffer (to fread()) does not directly arises from "fileBuffer is of type char **" but from the fact that (the memory to be read into) had been allocated to *fileBuffer (by this call *fileBuffer = malloc(fileSize + 1);).
@alk sir, updated the answer, can you please review whether it is proper now?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.