NB borrowed some comments from other answers and integrated into the whole. The code is all mine ...
- Check for error codes. For instance. malloc can return NULL if there is no memory. This can lead to interruption of your data.
- sizeof (char) - 1 by definition
- Use snprintf rather than sprintf to avoid buffer overflows
- If EZMPPOST etc. are constants, then you do not need a format string, you can simply combine several string literals like STRING1 "STRING2" "STRING3 and strcat of the entire batch.
- You are using a lot more memory than you need.
- With one minor change, you do not need to call memset first. Nothing really requires zero initialization.
This code does the same, is safe, runs faster, and uses less memory.
// sizeof(char) is 1 by definition. This memory does not require zero // initialisation. If it did, I'd use calloc. const int max_msg = 2048; char *msg = (char*)malloc(max_msg); if(!msg) { // Allocaton failure return; } // Use snprintf instead of sprintf to avoid buffer overruns // we write directly to msg, instead of using a temporary buffer and then calling // strcat. This saves CPU time, saves the temporary buffer, and removes the need // to zero initialise msg. snprintf(msg, max_msg, "%s %s/%s %s%s", EZMPPOST, EZMPTAG, EZMPVER, TYPETXT, EOL); //Add Data size_t len = wcslen(gdevID); // No need to zero init this char* temp = (char*)malloc(len); if(!temp) { free(msg); return; } wcstombs(temp, gdevID, len); // No need to use a temporary buffer - just append directly to the msg, protecting // against buffer overruns. snprintf(msg + strlen(msg), max_msg - strlen(msg), "%s: %s%s", "DeviceID", temp, EOL); free(temp);
source share