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.
void delay(unsigned int mseconds)
clock_t goal = mseconds + clock();
while (goal > clock());
int LCDSize = 10;
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)
int j = 0;
while (j < 2)
for (int i = 0; i < MSGSize - LCDSize + 1; i++)
tmpMSG = MSG+i;
strncpy(LCD, tmpMSG, LCDSize);
strncpy(LCD, tmpMSG, LCDSize); strcat(LCD,"\0");
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.
strcat function appends one string onto another. Both strings must be legal, well-formed strings or you must not call
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.