【发布时间】:2016-11-25 18:30:29
【问题描述】:
我有一个示例代码,它应该以 LCD 显示器(运行文本)的方式写入“MSG”,当它到达末尾时它会再次开始,但是当我为“LCD”分配内存时(应该是 10 个字符+终止 0) 用一堆随机字符填充它。 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)
{
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);。这里不是很重要,因为用户无法控制消息的内容并且消息不包含百分号(如果一切正常的话),但通常对于用户提供的要打印的数据,您使用的内容可能是致命的。它们被称为“格式字符串漏洞”。