【发布时间】:2011-06-26 05:39:13
【问题描述】:
我正在编写一个套接字程序来下载图像。问题是当我在像 gif 这样的小图片上测试我的代码时,它工作正常。但是当我使用 JPG 图片(比 GIF 大)运行它时,我收到了错误消息:
*** glibc detected *** /home/ubuntu/NetBeansProjects/myDownloader/dist/Debug/GNU-Linux-x86/mydownloader: free(): invalid next size (normal): 0x0a03c978 ***
请查看代码,我将提供有关错误的更多信息。
FILE* pFile;
long lSize;
unsigned char* buffer;
size_t result;
FILE* combinedFile = fopen("mypic.jpg", "wb+");
for(i = 1; i <= numberOfPartitions; i++)
{
sprintf(filename, "part%d", i);
pFile = fopen(filename, "rb");
//obtain file size
fseek(pFile , 0 , SEEK_END);
lSize = ftell(pFile);
rewind(pFile);
// allocate memory to contain the whole file:
buffer = (unsigned char*) malloc(sizeof(unsigned char) * (lSize + 1));
if(buffer == NULL)
{
fputs("Memory error", stderr);
exit(2);
}
// copy the file into the buffer:
result = fread(buffer, 1, lSize, pFile);
if(result != lSize)
{
fputs("Reading error", stderr);
exit(3);
}
else
{
unsigned char* temp = strstr(buffer, "\r\n\r\n");
temp = temp + 4;
int len = lSize - (temp - buffer);
//printf("i : %d len is : %d plen is %f\n",i,len,pLen);
if(i != numberOfPartitions)
fwrite(temp, 1, len - 1, combinedFile);
else
fwrite(temp, 1, len, combinedFile);
}
fclose(pFile);
printf("crash here\n");
free(buffer);
}
fclose(combinedFile);
我从这部分得到了错误,正如我所说的,当图像尺寸很小时它可以正常工作。但是更大的尺寸它坏了! P.S:程序将图片分成几个文件,然后重新组合,所以组合部分是导致错误的部分。
任何帮助将不胜感激,因为我已经被这个错误困住超过 3 天了!
【问题讨论】:
-
唯一让我兴奋的是
strstr(buffer,"\r\n\r\n");。为什么要在二进制文件中搜索(Windows 风格的)返回字符? -
确定通过套接字响应的标头的结尾。这是丢弃此标头并开始复制二进制数据的唯一方法。
-
当有多个“分区”时,这些“分区”是否都包含
"\r\n\r\n"序列? -
您好,实际上每个分区都是通过执行不同的 GET 请求生成的。因此,它们中的每一个都包含“\r\n\r\n”。当循环到达空闲(缓冲区)时完成第一次迭代时会发生问题!
-
仅供参考,Valgrind,可能在您的发行版的包管理器中可用,是帮助处理此类事情的好工具。