简体   繁体   English

尝试通过指针到指针函数调用为字符串分配内存时出现分段错误

[英]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. 此函数的目的是获取file.txt的内容并将其放入fileBuffer变量中。 Because the content of file.txt is dynamic, I allocate the memory for fileBuffer dynamically in the readFileToBuffer() function like so: 因为file.txt的内容是动态的,所以我在readFileToBuffer()函数中动态地为fileBuffer分配内存,如下所示:

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. 我已经用Google搜索了,这似乎是在函数内部分配内存时的正确方法。

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); readFileToBuffer()代码中, fileBuffer的类型为char ** ,您的函数被称为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() ]. 然后你正确地将内存分配给readFileToBuffer() *fileBuffer [ 这样就会被反映到main()fileBuffer So, you need to pass *fileBuffer to fread() to read the contents of the files into the memory pointed by *fileBuffer . 因此,您需要将*fileBuffer传递给fread()以将文件内容读 *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. 始终检查malloc()的返回值是否成功。
  2. The recommended signature for main() is int main(void) . main()的推荐签名是int main(void)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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