Below is a function from a program:
//read the specified file and check for the input ssn
int readfile(FILE *fptr, PERSON **rptr){
int v=0, i, j;
char n2[MAXS+1], b[1]=" ";
for(i=0; i<MAXR; i++){
j=i;
if(fscanf(fptr, "%c\n%d\n%19s %19s\n%d\n%19s\n%d\n%19s\n%19s\n%d\n%d\n%19s\n\n",
&rptr[j]->gender, &rptr[j]->ssn, rptr[j]->name, n2, &rptr[j]->age,
rptr[j]->job, &rptr[j]->income, rptr[j]->major, rptr[j]->minor,
&rptr[j]->height, &rptr[j]->weight, rptr[j]->religion)==EOF) {
i=MAXR;
}
strcat(rptr[j]->name, b);
//strcat(rptr[j]->name, n2);
if(&rptr[MAXR]->ssn==&rptr[j]->ssn)
v=j;
}
return v;
}
the commented line is like that because for some reason the array ‘b’ contains the string ‘n2’ despite an obvious lack of an assignment. This occurs before the first strcat call, but after/during the fscanf call.
it does accomplish the desired goal, but why is n2 concatenated onto the end of b, especially when b only has reserved space for 1 array element?
Here is a snippet of variable definitions after the fscanf call:
*rptr[j]->name = "Rob"
b = " Low"
n2= "Low"
It works, because you got lucky.
bandn2happened to be next to each other in memory, in the right order. C doesn’t do boundary checking on arrays and will quite happily let you overflow them. So you can declare an array like this:The C compiler (certainly old ones) is going to think this is fine, even though there clearly isn’t enough space in the
someArrayto store that many characters. I’m not sure if it’s defined what it’ll do in this situation (I suspect not), but on my compiler it limits the population to the size of the array, so it doesn’t overflow the boundary (someArray=={'l'}).Your situation is the same (although less extreme).
char b[1]is creating an array with enough room to store 1 byte. You’re putting a space in that byte, so there’s no room for the null terminator.strcat, keeps copying memory until it gets to a null terminator, consequently it’ll keep going until it finds one, even if it’s not until the end of the next string (which is what’s happening in your case).If you had been using a C++ compiler, it would have thrown at least a warning (or more likely an error) to tell you that you were trying to put too many items into the array.