Cereal
Cereal

Reputation: 3849

Why would the output of a program change between computers

This is homework, but I haven't gotten any closer to the answer after searching for an hour.

Consider the following program:

#include <stdio.h>
#include <string.h>
int main(){
  char s[10], t[10];
  int i, j;

  strcpy(s, "frog");
  for(i=0; i<strlen(s); i++)
    t[i] = s[i];
  j = 0;
  for(i=0; i<strlen(t); i++)
     j = j+(int)t[i];
  printf("%d\n", j);
  return 0;
}

The expected output of this program is 430, but it often produces a different result. The result seems to change depending on when the program is run, or on which computer it is run. Why?

From what I understand, strcopy will make s = {'f','r','o','g','\0',..}, and strlen(s) will always return 4. Running through the following loop, t = {'f','r','o','g',..}. The only way I can see it returning something other than 430 is if t had a value other than \0 after the g, causing strlen(t) to return something greater than 4.

So, if I'm correct in thinking the problem arises in that t might not have a \0 in the fifth position of the array, can someone explain to me why?

Upvotes: 1

Views: 296

Answers (2)

John3136
John3136

Reputation: 29266

String t is not 0 terminated so the call to strlen(t) will result in undefined behavior.

Upvotes: 0

user229044
user229044

Reputation: 239392

Sure, strcpy might insert a null byte, but you're definitely not copying that \0 across in your for i = 0; i < strlen(s); i++) loop...

Upvotes: 4

Related Questions