高手请看--莫名其妙的bug求解

dushuchen 2010-10-16 10:31:41
#include "stdio.h"
#include "stdlib.h"
#include "time.h"

#define passwordLength 9 //including the last char '\0'

//generate 8-bit password
char* GeneratePassword()//unnessesary to change, so return the point
{
char* password = new char[passwordLength];//password vector
for(int i = 0; i < passwordLength; i++)
{
password[i] = '\0';
}
char passwordElements[62] = {'0','1','2','3','4','5',
'6','7','8','9','a','b',
'c','d','e','f','g','h',
'i','j','k','l','m','n',
'o','p','q','r','s','t',
'u','v','w','x','y','z',
'A','B','C','D','E','F',
'G','H','I','J','K','L',
'M','N','O','P','Q','R',
'S','T','U','V','W','X',
'Y','Z'};
srand((unsigned int)time(NULL));
int index = 0;
for(i = 0; i < passwordLength-1; i++)
{

index = rand() % 61;//generate an int from 0 to 61
password[i] = passwordElements[index];
}
return password;
}

//test process
int main(void)
{
char* test = NULL;
//test = GeneratePassword();

for(int j = 0; j < 10; j++)
{
test = GeneratePassword();
printf("%s\n", test);
}

//printf("%s\n", test);
delete[] test;
return 0;
}
本程序产生10个不同的随机8位密码
debug的时候发现产生的不一样
但是打印的都一样
请高手帮忙改错

本程序在vc++ 6.0下可以运行
...全文
132 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
dushuchen 2010-10-17
  • 打赏
  • 举报
回复
受益匪浅 受益匪浅
MATHPHYSIC 2010-10-17
  • 打赏
  • 举报
回复
楼上的都是高手!!受益匪浅啊
a919457497 2010-10-17
  • 打赏
  • 举报
回复
是因为在同一个函数中调用,程序执行很快导致系统返回的时间基本一样吗
fibbery 2010-10-16
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 yangsen600 的回复:]
C/C++ code

srand((unsigned int)time(NULL));//放在main()里面啊,切记。
[/Quote]

支持:)
fibbery 2010-10-16
  • 打赏
  • 举报
回复
优化的建议:
char passwordElements[62];
可以在函数中定义为局部静态变量,也就是
static char passwordElements[62];
这样可以提高程序运行效率。
千杯不醉-sen 2010-10-16
  • 打赏
  • 举报
回复

srand((unsigned int)time(NULL));//放在main()里面啊,切记。
litolyan 2010-10-16
  • 打赏
  • 举报
回复
补充一下,srand((unsigned int)time(NULL));这个函数在你直接跑的时候,可能由于每次time(NULL)的调用返回值都相同,导致无法产生随机数,所以后面的rand()函数每次的返回值都一样,但是单步调试就不会,因为系统时间值的变化较大。
litolyan 2010-10-16
  • 打赏
  • 举报
回复
楼主,你这个需要去掉srand((unsigned int)time(NULL));这一句,因为你调试的时候,这个值每次获取到的差异很大,但是你直接跑的话,这个值每次获取到的都不变,你只要去掉这一句,程序就可以达到你要的效果,但是你这个还存在一个问题,就是内存泄露。
你每调用一次GeneratePassword()函数,都会分配一次内存,而你的代码调用了该函数十次,却只释放了一次。建议将password改为静态数组,这样就可以简单的避免掉内存泄露问题

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧