简体   繁体   中英

Segmentation fault when trying to allocate memory for a string via a pointer-to-pointer function call

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?

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) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM