Man Person
Man Person

Reputation: 1130

C taking string data from file, outputting some unexpected results

So I have a makefile type file where I'm first trying to take each line of said file and store it into a an array of strings, each index of the array is a separate line. I have found that this part of the code works alright, but then I take that array of strings and I try to take each individual file that is independent and dependent from the makefile, I output the string array and it outputs as follows:

util.hmain.c stk.o util.o▒-▒
util.cmain.c stk.o util.o▒-▒
stk.hcmain.c stk.o util.o▒-▒
stk.ccmain.c stk.o util.o▒-▒
main.cmain.c stk.o util.o▒-▒
f▒c▒H▒▒ [Ð▒▒▒▒▒▒▒▒▒▒▒▒▒▒H▒▒8L▒D$PH▒T$HI▒▒L▒L$XeH▒

I'm really confused on why it's outputting such weird characters, is it a memory leak or something? I don't know how to fix it at all.

This is the following code which produces such an output..

char c;
int newline_count = 0;
while ( (c=fgetc(makeFile)) != EOF ) {
    if ( c == '\n' )
        newline_count++;
}

//Inputting file string data into a array of char arrays for simplicity.
char *fileString[newline_count];
rewind(makeFile);
int i;
int i2 = 0;
int i3 = 0;

for(i = 0; i < string_size; i++){
    char temp[500];
    temp[i3] = fgetc(makeFile);
    if(temp[i3] == '\n'){
        temp[i3] = '\0';
        fileString[i2] = strdup(temp);
        i2++;
        i3 = 0;
    }else{
        i3++;
    }
}


//Getting each individual file
char *files[newline_count];
for(i = 0; i < newline_count; i++){
    char temp[500];
    if(strstr(fileString[i], ":") != NULL){

    }else{
        i2 = 0;
        do{
            temp[i2] = fileString[i][i2];
            i2++;
        }while(!isspace(fileString[i][i2]));
        files[i] = strdup(temp);
    }
}


for(i = 0; i < newline_count; i++){
    printf("%s %c", files[i], '\n');
}

Any sort of insight would be helpful, I'm just stuck.

Upvotes: 0

Views: 165

Answers (1)

Paul92
Paul92

Reputation: 9062

Here:

    do{
        temp[i2] = fileString[i][i2];
        i2++;
    }while(!isspace(fileString[i][i2]));

you copy characters from fileString to temp without checking for string end. You should replace the condition with:

    }while(!isspace(fileString[i][i2]) && fileString[i][i2]!='\0');

But this is not enough, as it stops when it reaches '\0' and does not copy it. So, after that, you should add:

temp[i2] = '\0';

Also note that strdup function allocates memory that you need to free, otherwise you have some memory leaks.

Upvotes: 1

Related Questions