-1

What is the problem with this code sample? I get either I segmentation fault, or program continues to run infinitely.

const char* prefix = "gender_";
char sex[8];                    

int id;
for(id=0; id <= 9 id++)           
{
    sprintf(id_string, "%i", id);           //converts int id to string id
    strcpy(sex, prefix);
    strcat(sex, id)
}

//sex should look something like this: gender_1, gender_2, gender_3 ... gender_9

M.M
  • 138,810
  • 21
  • 208
  • 365
nikk
  • 2,627
  • 5
  • 30
  • 51
  • hey @Matt, I think I mixed names up here. Apologies. I dint know who did. Thanks for the great answer! – nikk Mar 23 '15 at 00:27

1 Answers1

2

You overflowed your buffer. You're forgetting that strings have a null terminator.

Instead of writing fragile code like this that has a high chance of being exploitable, do:

char sex[9];
snprintf(sex, sizeof sex, "%s%i", prefix, id);

Using snprintf, even if you get the buffer size wrong, at least it does not cause a buffer overflow. Of course it could still be a bug, so you really do have to take care about your buffer sizes.

One option would be to declare sex with the size you wanted, instead of a magic number:

char sex[sizeof "gender_0"];

or

char sex[strlen(prefix) + 1 + 1];  // 1 for the digit, 1 for the terminator

The sizeof a string literal includes the null terminator.

M.M
  • 138,810
  • 21
  • 208
  • 365