Phlox Midas
Phlox Midas

Reputation: 4349

Garbage after string

I've written code to copy a string into another string but with a space between each character. When I run the code there is "garbage" after the string. However, if the for loop at the end is uncommented, there is no garbage after. Anyone know why this is happening?

#include<stdio.h>
#include<string.h>

#define MAX_SIZE 20
main ()
{
    char name[MAX_SIZE+ 1]; 
    char cpy[(MAX_SIZE * 2) + 1];

    gets(name);

    int i = 0;

    while (name[i] != '\0' && i < MAX_SIZE)
    {
        cpy[(i * 2)] = name[i];
        cpy[(i * 2) + 1] = ' ';
        i++;
    }

    cpy[strlen(cpy)] = '\0';    

    printf("%s\n", cpy);

    //for (i = 0; i < strlen(cpy); ++i) {
    //    printf("%c", cpy[i]);
    //}

}

Upvotes: 0

Views: 148

Answers (4)

bitmask
bitmask

Reputation: 34628

For the sake of completeness:

char* pcpy = cpy;
for (char const* p = fgets(name,sizeof(name)/sizeof(*name),stdin); p && *p; ++p) {
  *pcpy++ = *p;
  *pcpy++ = ' ';
}
*pcpy = 0;

You should use fgets, not gets in order to prevent your stack to be corrupted by data overruns. Second, You must manually terminate the string stored in the cpy array, since strlen simply counts the number of characters until the very first zero. Hence, if you haven't already terminated cpy the result of strlen(cpy) will be undefined and most likely crash your program.

Upvotes: 1

Joze
Joze

Reputation: 1305

Because you know that you are working with a string, it's a good thing if you initialize your "cpy" array with null character :

 char cpy[(MAX_SIZE * 2) + 1]  = "\0";

Otherwise, I agreed with simonc answer.

Upvotes: 1

simonc
simonc

Reputation: 42175

The line

cpy[strlen(cpy)] = '\0';

won't work since cpy isn't null terminated so strlen will read beyond the end of name until it either crashes or finds a zero byte of memory. You can fix this by changing that line to

cpy[i*2] = '\0';

If uncommenting the for loop at the end of your function appears to fix things, I can only guess that i gets reset to 0 before your printf call, meaning that printf finds a null terminator on the stack immediately after cpy. If this is what's happening, its very much undefined behaviour so cannot be relied upon.

Upvotes: 5

jim mcnamara
jim mcnamara

Reputation: 16379

 while (name[i] != '\0' && i < MAX_SIZE)
    {
        cpy[(i * 2)] = name[i];
        cpy[(i * 2) + 1] = ' ';
        i++;
    }
 cpy[(i * 2)] = 0x0;

You have to null terminate the string.

Upvotes: 2

Related Questions