/*
* 1-20. Write a program detab that replaces tabs in the input with the proper number
* of blanks to space to the next tab stop. Assume a fixed set of tab stops, say every n columns.
* Should n be a variable or a symbolic parameter?
*
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define N 4
void detab(char **str);
int main(){
char *line=NULL;
char *newline;
int len;
while(getline(&line,&len,stdin)!=-1){
detab(&line);
printf("%s",line);
}
free(line);
return 0;
}
void detab(char **str){
int len=0,num=0;
int i=0;
char c;
while((c=(*str)[i])!='\0'){
if(c=='\t'){ // get the number of tab
num++;
}
len++; // get length of string
i++;
}
char *newline;
newline=(char *)malloc(len+(N-1)*num+1); //use four blank replace one tab
if(newline==NULL){
fprintf(stderr,"can't malloc space\n");
}
i=0;
int j=0; //index of newline
while((c=(*str)[i])!='\0'){
if(c=='\t'){
int k;
for(k=0;k<N;k++){
newline[j]=' ';
++j;
}
}
else{
newline[j]=c;
++j;
}
++i;
}
newline[j]='\0';
free(*str);
*str=newline;
}
이 제대로 작동 몇 가지 문제가 발생하지만 어쩌면 50 문자의 긴 문자열을 입력하면,이 말한다 :C 프로그래밍 언어 (K & R) ex1-20. 나는 짧은 문자열을 입력하면
*** Error in `./a.out': free(): invalid next size (fast): 0x0961b068 ***
Aborted (core dumped)
거의 여기 붙어있다 세 시간. 도와주세요. 나는 이중 연결리스트로 각 입력 라인을 읽고 문제 1_20 해결
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define N 4
char* detab(char *str);
int main(){
char *line=NULL;
char *newline;
int len;
while(getline(&line,&len,stdin)!=-1){
newline = detab(line);
printf("%s",newline);
free(newline);
}
free(line);
return 0;
}
char* detab(char *str){
int len=0,num=0;
int i=0;
char c;
while((c=str[i])!='\0'){
if(c=='\t'){
num++;
}
len++;
i++;
}
char *newline;
newline=(char *)malloc(len+(N-1)*num+1); //use four blank replace one tab
if(newline==NULL){
fprintf(stderr,"can't malloc space\n");
}
i=0;
int j=0; //index of newline
while((c=str[i])!='\0'){
if(c=='\t'){
int k;
for(k=0;k<N;k++){
newline[j]=' ';
++j;
}
}
else{
newline[j]=str[i];
++j;
}
++i;
}
newline[j]='\0';
return newline;
}
가 [malloc을 (친구)의 결과를 캐스팅하지 마십시오 (http://stackoverflow.com/q/605845). 또한, 할당 실패를 확인하는 것이 좋지만 'stderr'에 쓰는 대신'abort()'또는 다른 것을 사용해서는 안됩니까? – Deduplicator
'getline'은 포인터뿐만 아니라 버퍼에 대한 포인터를 기대합니다. 그것을 확인하십시오 [여기] (http://crasseux.com/books/ctutorial/getline.html) – dmg
내가 볼 수있는 유일한 오류는'getline()'의 두 번째 인수는'size_t *'가 아니라 'int *'. 오류를 일으키는 데 사용 된 긴 문자열의 예를 들려 줄 수 있습니까? valgrind 또는 수동 검사 중 하나를 사용하여 오류를 트리거 할 수 없었습니다. –