Hy我有一个示例代码bleow,它应该以液晶显示器(正在运行的文本)的方式写入“MSG”,并且当它到达结尾时它会再次发生切换,但是当我为“LCD”分配内存(可以是10个字符+终止0)用一堆随机字符填充它。 Sample picture为char分配内存时奇怪的字符*
#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)
{
printf(MSG);
}
else
{
char* tmpMSG;
int j = 0;
while (j < 2)
{
for (int i = 0; i < MSGSize - LCDSize + 1; i++)
{
tmpMSG = MSG+i;
strncpy(LCD, tmpMSG, LCDSize);
strcat(LCD,"\0");
printf(LCD);
delay(200);
system("cls");
}
printf("----------");
j++;
}
}
getchar();
return 0;
}
可能是什么问题呢?
使用'printf(MSG);'不是一个好主意;你应该使用'printf(“%s”,MSG);'。这里并不重要,因为用户无法控制消息的内容,并且消息中不包含百分号(如果一切正常),但通常用户提供的数据可以打印,所用的内容可能会致命。他们被称为“格式字符串漏洞”。 –