Razero Razero - 3 months ago 29
C Question

Weird characters when allocating memory for char*

Hy I have a sample code bleow, which should write the "MSG" in a way an LCD display would (running text) and when it reached the end it strarts again, but when I allocate memory for the "LCD" (which schould be 10 character+terminating 0) fills it with bunch of random characters.
Sample picture

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

void delay(unsigned int mseconds)
clock_t goal = mseconds + clock();
while (goal > clock());

int main()

int LCDSize = 10;
int MSGSize;
char* LCD = (char *)malloc(LCDSize+1);
char* MSG = (char *)malloc(80);
MSG = "This is a long message, probabli will move.";
MSGSize = strlen(MSG);
if (MSGSize <= LCDSize)
char* tmpMSG;
int j = 0;
while (j < 2)
for (int i = 0; i < MSGSize - LCDSize + 1; i++)
tmpMSG = MSG+i;
strncpy(LCD, tmpMSG, LCDSize);


return 0;

What could be the problem?

            strncpy(LCD, tmpMSG, LCDSize);

The strncpy function will not terminate if it doesn't fit. In this case, it doesn't fit. So there is no termination. Something that is not terminated with a zero byte is not a legal string, so you cannot pass a pointer to it as the first parameter to strcat, but you do.

The strcat function appends one string onto another. Both strings must be legal, well-formed strings or you must not call strcat.

This is one of the reasons it is generally suggested that you not use strncpy -- there is no guarantee the result is a valid string and it's easy to make the kind of mistake you made. Yes, you made sure you didn't overflow the buffer when you called strncpy by limiting the size, but you didn't ensure the buffer contained a valid string.

What you probably wanted was LCD[LCDSize]='\0'; instead of the call to strcat. This ensures the buffer is terminated.