我正在尝试将一个大的二进制文件写入 C++ 程序的缓冲区中。在尝试创建与文件读取大小相同的缓冲区后,GDB 总是会出现段错误。它要么在 fclose(pf)、倒带或 f(open) 上失败,这让我相信当我尝试创建缓冲区时出现了问题。我的代码段如下。
static int fileTransfer(struct mg_connection *conn, char * filename){
FILE *fp = fopen(filename, "r");
fseek(fp, 0, SEEK_END);
int size = ftell(fp);
char buf[size];
fclose(fp);
// This is an attempt to stop a segment fault from rewind.
fp = fopen(filename, "r");
conn->connection_param = (void *) fp;
size_t n = 0;
if(fp != NULL)
{
n = fread(buf, 1, sizeof(buf), fp);
mg_send_data(conn, buf, n);
if(n < sizeof(buf) || conn->wsbits != 0)
{
fclose(fp);
conn->connection_param = NULL;
}
}
return 1;
}
我尝试将打印语句放入此代码中,但它们不会打印到控制台,因为它们在单独的线程中运行。有人可以给我一些关于为什么会发生此段错误的见解,或者一些关于如何使此代码更高效的建议。
我应该注意到,这段代码可以在 1 MB 和 10 MB 文件上正常工作,但不能在更大的文件上工作。
永远不要这样做:
int size = ftell(fp);
char buf[size];
您正在堆栈上创建大小,而不是堆上......堆栈上的 100MB 不起作用。
并且...大小必须是常量,而不是来自以下位置的数字ftell()
。我什至不知道它是如何编译的......
你必须做的是使用分配内存malloc()
or new
操作员。
static int fileTransfer(struct mg_connection *conn, char * filename){
FILE *fp = fopen(filename, "r");
fseek(fp, 0, SEEK_END);
int size = ftell(fp);
char * buf = new char[size]; // fix also here!
fclose(fp);
// This is an attempt to stop a segment fault from rewind.
fp = fopen(filename, "r");
conn->connection_param = (void *) fp;
size_t n = 0;
if(fp != NULL)
{
n = fread(buf, 1, size, fp); // fix also here!
mg_send_data(conn, buf, n);
if(n < size || conn->wsbits != 0)
{
fclose(fp);
conn->connection_param = NULL;
}
}
delete [] buf; // and you have to deallocate your buffer
return 1;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)