我寫了一個程序來生成一個隨機字符串, 但是當我調用兩次/多次的函數,我得到相同的隨機字符串。如何清除C中的內存?
請檢查下面的代碼:
#include <string.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
char* randomstring(int length);
int main()
{
char* randomstring(int);
char *str, *str2;
str = randomstring(3);
str2 = randomstring(3);
printf("final random string is %s and length is %s\n", str, str2);
}
char* randomstring(int length)
{
int len, len1, i = 0, j = 0;
char *c;
char *string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
len = strlen(string);
len1 = length + 1;
time_t t;
c=(char*) calloc(len1, sizeof(char));
printf("final random string is %d \n", len);
srand((unsigned) time(&t));
for(i = 0; i < length; i++)
{
j=rand() % len;
c[i] = string[j];
}
c[len1] = '\0';
return c;
}
輸出:
final random string is 26
final random string is 26
final random string is BNQ and length is BNQ
[請參閱爲什麼不投的malloc'的返回值這個討論( )'和家庭在'C'。](http://stackoverflow.com/q/605845/2173917)。 –
在開始處移動'char * randomstring(int);'...... –
從現在開始,請正確縮進您的代碼,否則沒有人能夠讀取它。 – birdoftheday