这是我的代码:
#include <stdlib.h>
#include <stdio.h>
int sendMessage(uint8_t *pui8MsgData, int messageLength, uint32_t ui32ObjID)
{
int total = 0;
int bytesleft = messageLength;
int n;
int chunkSize;
while (bytesleft)
{
chunkSize = bytesleft > sizeof(uint8_t)*8 ? sizeof(uint8_t)*8 : bytesleft;
uint8_t *buffer = (uint8_t *)malloc(sizeof(uint8_t) * chunkSize);
if(buffer == NULL)
{
printf("Memory allocation failed");
return 0;
}
memcpy(buffer, pui8MsgData, sizeof(uint8_t) * chunkSize);
n = send(buffer, chunkSize, ui32ObjID);
total += n;
bytesleft -= n;
}
return 1;
}
Run Code Online (Sandbox Code Playgroud)
但由于某种原因,malloc总是返回NULL ..什么可能是错的?或者如何获取malloc返回的错误?
这是不可能100%确定地告诉你这里有什么问题; 信息太少了.
然而,这malloc()似乎毫无意义,你永远不会free().这是内存泄漏,这可能解释了为什么内存不足导致malloc()返回NULL.对我来说似乎有道理.
只需将数据直接传递给send(),无需分配新的缓冲区并复制数据.
编辑:此外,您永远不会更新,pui8MsgData因此您一遍又一遍地处理邮件的第一个字节.
总而言之,循环应该是这样的:
while (bytesleft)
{
const chunkSize = bytesLeft > 8 ? 8 : bytesLeft;
const ssize_t n = send(ui32ObjID, pui8MsgData + total, chunkSize);
if (n < 0)
{
fprintf(stderr, "Send() failed\n");
return 0;
}
total += n;
bytesLeft -= n;
}
Run Code Online (Sandbox Code Playgroud)
这通过删除修复了问题malloc().我还将参数交换为send(),假设ui32ObjID是一个有效的文件描述符.