虽然我能够纠正我的程序并使其正常运行,但它不工作的原因让我非常好奇。
我用 malloc 创建了一个字符串并对其进行了初始化……然后我用它做了几个 strcat……然后我声明了一个文件指针……在那之后,如果我的字符串有超过大约。 26 个字符,其余的将是垃圾...但是如果我之前将指针声明为字符串 malloc,它会很好用。我只是不明白为什么,这里是一些代码,如果有人认为最好看到更多,请这样说:
代码:
char* holder=(char*)malloc(sizeof(char)*100);
for(i=0;i<100;i++)
*(holder+i)='\0';
strcat(holder,"set xtics (");
//will ignore until the last n lines
for(i=0;i<26-n;i++)
readline(sfd,line,29);
//will manage the last lines
char n_column[2];
char freq[3]={0};
for(i;i<26;i++)
{
readline(sfd,line,29);
sscanf(line+4,"%s",freq);
write(out,freq,strlen(freq));
write(out,"\n",1);
strcat(holder,"'");
sscanf(line,"%s",temp);
strcat(holder,temp);
strcat(holder,"'");
sprintf(n_column,"%d",counter);
strcat(holder," ");
strcat(holder,n_column);
//for the las one which won't have the ,
if(i==25)
strcat(holder,")");
else
strcat(holder,", ");
counter++;
}
//sending to gnuplot using pipe
printf("Before: %s\n",holder);
FILE *pipe = popen("gnuplot -persist","w"); //why can't it be here!!!!
printf("After: %s\n",holder);
输出:
之前:set xtics ('a' 0, 'b' 1, 'c' 2, 'd' 3, 'e' 4, 'f' 5, 'g' 6, 'j' 7, 'k ' 8, 'l' 9, 'm' 10, 'n' 11, 'o' 12, 'p' 13, 'q' 14, 'r' 15, 'u' 16, 'v' 17, 'w ' 18, 'x' 19, 'y' 20, 'z' 21, 'h' 22, 'i' 23, 't' 24, 's' 25)
之后:设置 xtics ('a' 0, 'b' 1, 'c' 2, 'd' 3, 'e' 4, 'f' 5, 'g' 6, 'j' 7, 'k ' 8,'l' 9,'m' 10,'n' 11,'o'。
但是如果我改成:
FILE *pipe = popen("gnuplot -persist","w");
char* holder=(char*)malloc(sizeof(char)*100);
for(i=0;i<100;i++)
*(holder+i)='\0';
输出正常。
那么为什么声明文件指针会造成如此大的不同呢?或者除此之外还有什么?
非常感谢您的耐心等待。
最佳答案
你有一个 100 字节的缓冲区和 208 字节的字符串。那100字节之外的内存不属于你。
关于c - 填充 malloc() 分配的内存的效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1891864/