user3226932
user3226932

Reputation: 2252

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?

Upvotes: 0

Views: 359

Answers (1)

David Schwartz
David Schwartz

Reputation: 182829

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.

Upvotes: 4

Related Questions