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.