Home > Mobile >  C strcat inserts garbage into string
C strcat inserts garbage into string

Time:09-17

My method reads an input text of vectors with the following format:

57.0000,-7.4703,-0.3561
81.0000,-4.6478,7.9474
69.0000,-8.3768,0.4391
18.0000,-4.9377,9.9903
62.0000,-5.8751,-6.6054
...

My attempt to read each vector and insert it to an array is as follows:

FILE *file;
int n = 1, dim, i=0;
char* str;
double ret;
double* X;
int c;
int com=0;
assert(argc==2 && "argc != 2");
file = fopen(argv[1], "r");
assert(file && "file is empty");
for(c = getc(file); c!= EOF; c = getc(file)){
   if(c == '\n'){
        n  ;
   }
   else if(c==','){
       com  ;
   }
}
dim = com/n  1;
char* str;
double ret;
double* X;
X = (double *)calloc(n*n, sizeof(double));
assert(X); 
str = (char *)calloc(100, sizeof(char));
assert(str); 
for(c = getc(file); c!= EOF; c = getc(file)){
     if(c!=',' && c!= '\n'){
       strcat(str, &c);      
     }
     else{
     ret = strtod(str, NULL);
     X[i] = ret;
     i  ;
     memset(str, 0, 100 * sizeof(char)); 
     }
}

The problem is that when it gets to the last vector at each line, it reads each char and concatenates it with extra garbage into str. Any ideas how to solve this?

CodePudding user response:

strcat expects a NUL-terminated string (array of char) as its second argument, but c is defined as a single character, not an array of char.

To fix this, you can maintain an index into str

int c;
int j = 0;
for (c = getc(file); c!= EOF; c = getc(file)) {
    if (c != ',' && c != '\n') {
        str[j  ] = c;
        str[j] = 0; // keep string NUL-terminated
    } else {
        ret = strtod(str, NULL);
        X[i] = ret;
        i  ;
        // reset j
        j = 0;
    }
}

CodePudding user response:

As c is char the following is invalid.

c = getc(file); c!= EOF;  

and

strcat(str, &c);

Both are Undefined behaviours. To sort the first out declare c as int

The second problem:

//You need to create a null char terminated string to use as 
//second parameters of the srtcat. For example, you can define 
//a compound literal - char array containing two elements: c & 
//terminating null character
strcat(str,(char []){c,0});
  • Related