Home > Software design >  C File Handling Appending Random Characters into File
C File Handling Appending Random Characters into File

Time:03-20

The following block of code creates a string

void generateDot(struct node **head, char *str){
    if(*head == NULL){
        return;
    }
    else{
        struct node *itr = *head;

        generateDot(&(itr->left), str);
        if(itr->parent){
            char buff[3];
            snprintf(buff, 3, "%d", itr->parent->data);
            strcat(str, buff);
            strcat(str, "--");
            snprintf(buff, 3, "%d", itr->data);
            strcat(str, buff);
            strcat(str, "\n");
        }
        generateDot(&(itr->right), str);
    }
}

The following block of code writes the string to the file:

 char str[] = "";
 generateDot(&head, str);
 printf("%s", str);

 FILE *fhand = fopen("1.dot", "w");
 fputs(str, fhand);

 fclose(fhand);

When I am printing str, it prints as expected. However, even though the same str is being printed into the file, the second line of the file shows unexpected characters, regardless of what str is.

For example, when str is:

3--1
7--3
3--4
19--10
7--19
19--20

The file contains:

3--1
`F
w
3--4
19--10
7--19
19--20

Any help would be very much appreciated.

CodePudding user response:

When you strcat(str, buff) you're writing to adjacent, unallocated memory. This invokes undefined behavior, anything could happen.

When you print str the memory happens to be as you've written. But something in fopen and fputs allocates some more memory which overwrites the unallocated parts of str with garbage.

You need to allocate sufficient memory to str. Since you don't know how much memory is needed, you'd be better off doing the allocation and reallocation inside generateDot and return the string.

  • Related