我正在尝试生成应该存储在缓冲区数组中的uint_32随机数,但不知何故,我的代码每次只存储最后一个值。
例如,当我生成像
这样的随机数时12365645
97897875
45458788
然后是
的值buffer[0]=12365645
buffer[1]=97897875
buffer[2]=45458788
但是目前,我好像是
buffer[0]=45458788
buffer[1]=45458788
buffer[2]=45458788
这是我的相应代码,但不确定我在哪里犯了错误。
/*Required header files are added*/
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdint.h>
struct thread_arguments
{
char *buffer;
char *queue[10];
uint32_t offset;
uint32_t r;
size_t bufferlen;
size_t minlevel;
}ta;
void randomgenerate();
void constructor(int size, int filllevel);
void put_buffer(int ele);
void printbuf();
int main(void)
{
ta.offset=0;
ta.buffer=NULL;
constructor(1,3);
randomgenerate();
printbuf();
return EXIT_SUCCESS;
}
void constructor( int filllevel,int size)
{
//ta.buffer[size];
ta.bufferlen=size;
ta.minlevel=filllevel;
}
void randomgenerate()
{
int i;
for(i=0;i<ta.bufferlen;i++)
{
int myFile = open("/dev/random", O_RDONLY);
read(myFile, &ta.r, sizeof(ta.r)) ;
put_buffer(i);
close(myFile);
}
}
void put_buffer(int ele)
{
ta.buffer = realloc(ta.buffer, sizeof(uint32_t));
sprintf(ta.buffer, "%zu", ta.r);
ta.offset += sizeof(uint32_t);
ta.queue[ele]=ta.buffer;
printf("%d\t%s\n",ele,ta.queue[ele]);
}
void printbuf()
{
int k;
for(k=0;k<ta.bufferlen;k++)
{
printf("%s\n",ta.queue[k]);
}
}
答案 0 :(得分:1)
你在滥用realloc()
。您的ta.buffer
始终指向相同的ta.buffer
,因为它已经等于sizeof (uint32_t)
。因此,当您执行赋值ta.queue[ele] = ta.buffer
时,每个ta.queue
指针都是相同的值。
您需要的是malloc()
。
修改强>
对于malloc()
的每次通话,您应该使用put_buffer()
,如下所示:
void put_buffer (int ele)
{
/* There are 10 decimal digits (characters) in a 32-bit unsigned integer, + 1 for the null terminator */
ta.buffer = malloc ((sizeof *ta.buffer) * 11);
/* Print the string representation to the newly-allocated buffer */
sprintf(ta.buffer, "%u", ta.r);
/* I'm not sure what this is for so I'll leave it alone */
ta.offset += sizeof (uint32_t);
ta.queue[ele] = ta.buffer;
}
答案 1 :(得分:1)
每次使用realloc
不仅大小相同,而且分配的内存量也不对。
ta.buffer = realloc(ta.buffer, sizeof(uint32_t));
sprintf(ta.buffer, "%zu", ta.r);
sizeof(uint32_t)
将为4
。这个内存不足以以字符串形式存储uint32_t
类型的对象。
您的程序受到未定义的行为。