【发布时间】:2020-09-30 05:20:40
【问题描述】:
我在一个循环中,我想将读取的值从 fifo 保存在一个变量中。
char *tmp=NULL;
char *opts=NULL;
char break_[]="DONE\n";
int byte_;
while(1){
pipe_r = open(pipe_r_n, O_RDONLY);
if(pipe_r==-1){
exit(100);
}
read(pipe_r,&byte,sizeof(int));
opts=malloc((byte+1)*sizeof(char));
if (!opts) {
free(opts);
opts = NULL;
close(pipe_r);
exit(102);
}
read(pipe_r,opts,byte*sizeof(char));
printf("ho letto: %s",opts);
close(pipe_r);
if(strcmp(opts,break_)==0){
break;
}
free(opts);opts=NULL;tmp=NULL;
}
free(opts);opts=NULL;tmp=NULL;
byte_int 是后面需要读取的字节数。 它说在乞求中读取了 0 个字节,但也在打印(读取不等待(?))。然后它读取具有正确字节数的行,之后什么都没有,但具有相同的字节数......有时它会重复自己而不是什么都没有... 那是客户:
fd=fopen(argv[3],"r");
if(fd==NULL){
exit(100);
}
char *line=NULL;
size_t len=0;
ssize_t read;
int byte;
while ((read = getline(&line, &len, fd)) != -1) {
printf("%s\n",line);
pipe_r = open(pipe_r_n, O_WRONLY);
if(pipe_r==-1){
exit(100);
}
byte=strlen(line);
byte;
write(pipe_r,&byte,sizeof(int));
write(pipe_r,line,sizeof(char)*(strlen(line)));
close(pipe_r);
if(strcmp(line,"EXIT\n")==0){
break;
}
}
【问题讨论】:
-
不确定为什么是 realloc()。每次循环都在释放指针。此外,您不能在已释放的指针上合法地调用
strcmp。 -
现在
realloc使用:你可以调用`malloc/calloc` 和free每个循环或realloc,但realloc通常是为你想要保留内容时保留的重新分配期间的缓冲区。你没有,所以这将涉及不必要的额外工作。此外,每个循环都调用free()使得realloc完全不需要。不过,这并不能解释您现在看到的行为。检查read函数的返回码可能是个好主意,以确保它们读取的信息与您预期的一样多。 -
您不需要设置为始终免费,但这样做是一个好习惯。如果不设置为free,以后不小心使用了“悬空指针”,可能会导致Undefined Behavior。
-
在您的代码中,我也不确定您为什么需要 2 个指针。只需使用
opts看起来就足够了,并且会简化管理。 -
您应该重新发布更改的代码并仔细检查它是否仍然失败。我还站在
read返回值检查旁边。如果您读入的内容末尾没有\0终止符,则您的字符串打印 printf 将失败...
标签: c string pointers memory realloc