0

I have a simple program where I'm trying to learn about strcat and strcpy. However, it doesn't seem to be working quite right.

It seems to copy and append just fine. However, when I print I think it is accessing memory locations outside of its scope.

Here's the code:

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

int main(int sep, char ** arr)
{
    int i, size = sep;

    // Get size of whole string including white spaces
    for(i = 1; i < sep; i++)
        size += strlen(arr[i]) + 1;

    // Allocate memory
    char *ptr = malloc(size);

    for(i = 0; i < sep; i++)
    {
        // Copy first string then append
        if(i >= 1)
            strcat(ptr, arr[i]);
        else
            strcpy(ptr, arr[i+1]);

        //Replace null byte
        ptr[strlen(ptr)] = ' ';
    }

    // Add nullbyte to end
    ptr[strlen(ptr) + 1] = '\0';

    // Print whole string
    printf("\n%s\n\n", ptr);

    return 0;
}

If I pass this string: O_O hi o noe0x1828GFF2 32 32 32 3 23 2 3, it prints this:

O_O O_O hi o noe0x1828GFF2 ??32 ??t?32 ?̐?32 3 23 2 3

As you can see, it prints the first string until the whitespace twice as well as lots of characters that aren't even in the string.

What am I doing wrong here?

EDIT: Figured out the double string at the start. Just had to add +1 to arr[i] in strcat(ptr, arr[i]);. However, it still prints characters that are not in there.

If I take away this line: ptr[strlen(ptr)] = ' ', the weird characters aren't there but then it also leaves out white spaces.

neby
  • 103
  • 1
  • 2
  • 9

1 Answers1

1

With the line ptr[strlen(ptr)] = ' ';, you remove the terminating NULL character at the end of the string, interfering with subsequent calls to strlen() and strcat().

Try replacing with code that saves the terminating NULL:

ptr[strlen(ptr)+1] = '\0';
ptr[strlen(ptr)] = ' ';

or a more optimized version that does not call strlen() twice:

int len = strlen(ptr);
ptr[len] = ' ';
ptr[len+1] = '\0';
owacoder
  • 4,815
  • 20
  • 47
  • Thanks! Makes a lot of sense. Would you have any suggestions on what a more optimized version would be? I'm new to C and not sure what to look for. – neby Sep 19 '15 at 03:35