C 字符串标记器-已验证数组的奇怪行为
编辑以纳入编码和更新问题的建议 我必须在程序中实现一个自动换行功能,并选择了一个贪婪的算法C 字符串标记器-已验证数组的奇怪行为,c,unix,malloc,segmentation-fault,text-processing,C,Unix,Malloc,Segmentation Fault,Text Processing,编辑以纳入编码和更新问题的建议 我必须在程序中实现一个自动换行功能,并选择了一个贪婪的算法 //I use fread to take in the file in one bite, the parse the resulting array. The //four lines below are from another function. char *readBuffer= (char *) malloc(sizeof(char) * fileSize); int size=
//I use fread to take in the file in one bite, the parse the resulting array. The
//four lines below are from another function.
char *readBuffer= (char *) malloc(sizeof(char) * fileSize);
int size= ftell(fp);
rewind(fp);
size_t result= fread(readBuffer, 1, size, fp);
int spaceLeft= termWidth;
int outputLines=0, tempLength, printCount-0;
char *temp, *newLine="\n";
temp= strtok(readBuffer, " "),
fputs(temp, stdout); //prints out a 11, when should be a 1, then exits
while ((outputLines < termHeight) && (temp != NULL)){
strcat(temp, " ");
tempLength= strlen(temp);
if (spaceLeft > tempLength){
fputs(temp, stdout);
spaceLeft -= tempLength+1;
} else {
strcat(newLine, temp);
spaceLeft= termWidth-(tempLength);
outputLines++;
newLines="\n";
}
temp= strtok(NULL, " ");
printCount+= tempLength //debugger display
}
}
//我使用fread一口就把文件读入,然后解析生成的数组。这个
//下面四行来自另一个函数。
char*readBuffer=(char*)malloc(sizeof(char)*fileSize);
int size=ftell(fp);
倒带(fp);
size\u t result=fread(readBuffer,1,size,fp);
int spaceLeft=术语宽度;
int outputLines=0,模板长度,打印计数-0;
char*temp,*newLine=“\n”;
温度=strtok(读取缓冲区“”,
FPUT(温度、标准温度)//打印出一个11,当应该是1时,然后退出
while((输出线<终端高度)和&(温度!=NULL)){
strcat(温度,“”);
模板长度=标准长度(温度);
如果(空格左键>模板长度){
FPUT(温度、标准温度);
spaceLeft-=模板长度+1;
}否则{
strcat(换行,临时);
spaceLeft=术语宽度-(模板长度);
输出线++;
换行符=“\n”;
}
temp=strtok(空,“”);
printCount+=模板长度//调试器显示
}
}
通过这段代码,我验证了文件是否被一个
fputs(readBuffer,stdout)
命令。但是,第一个FPUT在屏幕上写入11,此时它应该是1。然后它跳过while循环并退出
OutputLines设置为0,termHeight是调用的结果
如果temp正在屏幕上打印一个值,并且(outputLines=0)>termHeight,那么在这种情况下temp怎么可能为空?部分问题可能是
fgets
仅从文件中检索一行。描述了这一点。代码似乎期望读取整个文件。因此,在处理第一行之后,temp将为NULL(如果其中没有空格,则为单个令牌)
由于不知道正在阅读的文本长度,也不知道termHeight
或termWidth
的值,因此无法知道执行路径。但是segfault可能发生在处理该行之后对NULLtemp
值的strlen()调用上。虽然这不是一个完整的修复,但是While
语句可能应该使用&&
而不是|
:
while ((outputLines > termHeight) && (temp != NULL){
根据您想要如何处理它,您可能需要另一个fgets
调用来读取strtok
返回NULL后的下一行。或者,使用在一次调用中检索整个文件。strtok
将返回null
,如果字符串中没有更多的标记,可能就是这样发生的?我是这么想的,但文件大小为1.6KB,其中包含大约90行文本。为什么它会返回null?如果我通过fputs
输出文本,而不使用strtok
,则会显示所有文本。文件中是否有任何NUL字符('\0')?这会干扰strtok()
。