Answer the question
In order to leave comments, you need to log in
Where is the error in the code, the symbol is lost, and free() does not work?
Hello, the program code is to process the input stream and write characters to an array,
in the del_spacetab function, I count how many spaces there are to the end of the line.
the question is that the lines after adding to the array are not displayed each on its own line. though I don't remove the newline characters. and the second question is why in the coppy function - the program crashes on free(p1) memory release? I can't figure out what's wrong. there are no errors when compiling. and warnings
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
int getlen(char **p1,char **p2);
void pprint(char **p1, int len);
int del_spacetab(char **p1,int len);
void coppy(char **p2,char **p1, int len_p2,int len,int *first_round);
int main(){
char *p1, *p2;
int len;
int len2;
int len_p2;
int len_max = 8;
int first_round =0;
p1 = (char*)malloc(1000 * sizeof(char));
p2 = (char*)malloc(1000 * sizeof(char));
len_p2=0;
while ((len = getlen(&p1,&p2)) >0){
if (len >= len_max){
len2 = del_spacetab(&p1,len);
len-=len2;
len_p2 += len;
coppy(&p2, &p1,len_p2,len,&first_round);
}
}
printf("Total:\n");
int i;
for (i=0;i<len_p2;++i){
printf("%c",p2[i]);
}
free(p2);
return 0;
}
int getlen(char **p1,char **p2){
int c, i;
for (i=0; (c=getchar()) != EOF && c != '\n'; ++i){
if (i==1000){
(*p1) = (char*)realloc(*p1, 100000 * sizeof(char));
(*p2) = (char*)realloc(*p2, 100000 * sizeof(char));
}
(*p1)[i]=c;
}
if (c == '\n'){
(*p1)[i]=c;
++i;
}
(*p1)[i]='\0';
return i;
}
void pprint(char **p1, int len){
int i;
for (i=0; i<len; ++i){
printf("%c",(*p1)[i]);
}
}
int del_spacetab(char **p1,int len){
int i;
int n=0;
for (i=0;i<len;i++){
if ((*p1)[i] == ' ' || (*p1)[i] == '\t' && (*p1)[i] != '\n'){
n++;
}
else if ((*p1)[i] != '\n'){
n=0;
}
if ((*p1)[i] == '\n'){
//n++;
return n;
}
}
}
void coppy(char **p2,char **p1,int len_p2,int len,int *first_round){
int i,n;
n=0;
if (*first_round == 0) {
*first_round=1;
i =0;
len=0;
}
else {
i=len_p2-len;
}
for (; i< len_p2; ++i){
(*p2)[i] = (*p1)[n];
n++;
}
free(*p1);
}
Answer the question
In order to leave comments, you need to log in
*** Error in `/home/a.out': double free or corruption (!prev): 0x0000000000d95010 ***
while ((len = getlen(&p1,&p2)) >0){
if (len >= len_max){
len2 = del_spacetab(&p1,len);
len-=len2;
len_p2 += len;
coppy(&p2, &p1,len_p2,len,&first_round);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question