Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate string with strcpy

Tags:

c

Here is my code

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


int main() {

 char f[] = "First";
 char s[] = "Second";
 char *tmp = malloc(strlen(f) + strlen(s) + 2);
 strcpy(tmp, f);
 strcpy(tmp, s);
 printf("%s", tmp);
 free(tmp);
 return 0;
}

I'm trying to concatenate f and s. The problem is that tmp contains only "Second" as a array. What I miss here

like image 719
pr1m3x Avatar asked Oct 23 '25 03:10

pr1m3x


2 Answers

strcpy copies the string to the beginning of the destination, you want strcat instead.

like image 190
Daniel Fischer Avatar answered Oct 24 '25 17:10

Daniel Fischer


The second strcpy overwrites the previous one. Both copy its content to the tmp pointer (at the start of it). You should use tmp+strlen(f).

Or even better use strcat.

And even better use more secure methods like: strncpy, strncat, etc..

like image 36
duedl0r Avatar answered Oct 24 '25 18:10

duedl0r