简体   繁体   中英

Dynamic C - char pointers, strcpy, strcat

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?

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.

func的大小+ msg的大小声明一个char数组,而不是未初始化的char指针。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM