简体   繁体   中英

2nd char array overwriting 1st char array after fread from file

Goal is to use C to read data from file (could be text or binary) and then append to an existing string

I have 2 char arrays, one an existing string (s1), and another a string (s2) I'll append the buffer char array (buf) to

size_t readCounter = 0;
char buf[16];
char s1[] = "hello ";
char s2[] = ""

while (1) {
    readCounter = fread(buf, sizeof(char), strlen(buf), fp);

    if (readCounter == 0) {
        break;
    }

    strcat(s2, buf);    
}

printf("%s", s1);
printf("%s", s2);

Problem:

When I print out s1, it no longer is "hello ", it includes the characters from the file so for some reason the first char array is being overwritten in memory. Why does this happen? How can I resolve this?

readCounter = fread(buf, sizeof(char), strlen(buf), fp);

This is a problem. At this point, buf doesn't contain a string, so passing it to strlen is an error.

Also:

char s2[] = "";
...
strcat(s2, buf);

This is not good. When you alllocated s2 , it pointed to an empty string. So the array was sized to hold an empty string. By passing s2 to strcat , you're trying to append onto it -- but it doesn't have any extra space.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM