[英]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, 那说,
malloc()
for success. 始终检查malloc()
的返回值是否成功。 main()
is int main(void)
. main()
的推荐签名是int main(void)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.