Q:

malloc fails and return NULL

this is my code:
#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;
}

but for some reason, the malloc always return NULL.. what could be wrong? or how to get the error which is returned by malloc?

A:

It is not possible to to tell you what is wrong here with 100% certainty; there's too little information.
However, the malloc() seems pointless, and you never free() it. This is a memory leak, which might explain why you run out of memory, causing malloc() to return NULL. Seems plausible to me.
Just pass the data directly to send(), no need to allocate a new buffer and copy data around.
Edit: also, you never update pui8MsgData so you're processing the first bytes of the message over and over.
So, to summarize, the loop should be something like:
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;
}

This fixes the problem by removing malloc(). I also swapped the arguments to send(), assuming ui32ObjID is a valid file descriptor.

