【问题标题】:How to clear the memory in C?如何清除C中的内存?
【发布时间】:2016-03-09 19:44:12
【问题描述】:

我写了一个程序来生成一个随机字符串, 但是当我两次/多次调用该函数时,我得到了相同的随机字符串。

请检查以下代码:

#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

【问题讨论】:

标签: c arrays pointers srand


【解决方案1】:

函数srand 设置随机种子,如果你用相同的随机种子再次调用它,它将导致未来的随机调用返回相同序列的重复。所以当你打电话时:

srand((unsigned) time(&t));

它将随机种子重置为以 为单位的挂钟时间。这意味着如果您在不到一秒后再次调用它(就像您在代码中所做的那样),它可能会将种子重置为相同的值,从而导致您再次获得相同的随机字符串。

你应该只调用srand一次,在你的程序开始时,在调用任何其他调用rand的函数之前

【讨论】:

  • 如果我删除 srand 函数,它会给出正确的输出吗?
  • 如果你完全删除srand,随机数生成器将以0为种子。所以它会给出“正确”的输出,但每次运行程序时都会给出相同的输出。每次运行程序时,将srand 调用放入main 将导致不同的输出(假设时钟在运行之间至少滴答一秒)
【解决方案2】:

首先,对于像这样的分配

c=(char*) calloc(len1,sizeof(char));

稍后,使用

c[len1]='\0';

正在访问超出范围的内存。它调用undefined behavior

为了详细说明,C 使用基于 0 的索引,因此,通过说

 c[len1]='\0';

你要去off-by-one

然后,您应该只调用一次 PNRG 种子函数 srand(),可能在 main()。否则,time() 的粒度为 1 秒,它将为 PNRG 播种相同的值,进而导致rand() 再次生成相同的随机数字集。

也就是说,

  1. Please see this discussion on why not to cast the return value of malloc() and family in C..

  2. sizeof(char) 在 C 中保证为 1。

编写分配语句的更好和健壮的方法是

c =  calloc( len1, sizeof*c );     

【讨论】:

    猜你喜欢
    • 2012-01-27
    • 1970-01-01
    • 2018-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-10
    • 2015-03-31
    • 1970-01-01
    相关资源
    最近更新 更多