0

Here is my code:

nodebug void sendLogPacketS(char *func, char *msg)
{
    char * log;
    memset(log, 0, strlen(func) + strlen(msg) + 1);
    strcpy(log, func);
    strcat(log, ": ");
    strcat(log, msg);
    sendUDPLogPacket(log, strlen(log));
}

It's supposed to take two strings, concatenate them together, then pass the new string and its length to a different function. I'm using Dynamic C 9.62, which doesn't have support for the malloc function, so I'm using memset instead.

The problem is when I printf the value of log before it's passed to sendUDPLogPacket, it contains garbage DynamiCUniversal Rabbit BIOS Version 9.50\?^>j. Anyone have any ideas why this isn't working?

Mike278
  • 35
  • 1
  • 3
  • 2
    `memset()` fills memory that's already been allocated. It does *not* allocate memory. `log` is pointing to a random location which (luckily) in your case doesn't seem to be writeable, so you're printing faulty data instead of just crashing. – Paul Roub Jun 16 '14 at 13:28

2 Answers2

2

Your code has undefined behavior.

You cannot validly access the memory pointed at by an uninitialized pointer, like you do.

The memset() function writes to memory, it does not magically allocate new memory (it takes as input the pointer to the memory to be written), you cannot in anyway use it "instead of" malloc().

You can try with an on-stack buffer:

char log[128] = "";

of course you need to take care not to use more than 128 characters; your unbounded strcat() usage is dangerous.

If your fringe compiler supports C99 you can of course do:

const size_t flen = strlen(func);
const size_t mlen = strlen(msg);
char log[flen + 2 + mlen + 1];  // Space for func, msg, colon, space, terminator.
unwind
  • 391,730
  • 64
  • 469
  • 606
0

Declare an array of chars with the size of func + size of msg instead of an uninitialized char pointer.

Sitram
  • 1,432
  • 1
  • 14
  • 17