thetux4
thetux4

Reputation: 1633

String concatenation in C

char *str1 = malloc(256*sizeof(char));
char *str2 = "stack"
for (i=0;i<15;i++){
     sprintf(str1,"%s%s",str1,str2);
} 
printf("%s\n",str1);

I'm trying to concat str2 to str1 at each loop count. But this code segment works but vulnerable. Whats the best way to concat them?

Upvotes: 0

Views: 464

Answers (4)

multipleinterfaces
multipleinterfaces

Reputation: 9163

Use strncat:

char *str1 = malloc(256*sizeof(char));
str1[0] = '\0';
char *str2 = "stack"
for (i=0;i<15;i++){
     strncat(str1, str2, 256 - 1 - strlen(str2));
} 
printf("%s\n",str1);

Upvotes: -1

brain
brain

Reputation: 2517

If you want to use sprintf; something like this:

char *str1 = malloc(256*sizeof(char));
char *str2 = "stack";
*str1 = '\0';
for (i=0;i<15;i++){
    snprintf(str1 + strlen(str1), 256 - strlen(str1), "%s", str2);
} 
printf("%s\n",str1);

Upvotes: 0

BlackBear
BlackBear

Reputation: 22979

The standard C function for string concatenation is char * strncat ( char * destination, char * source, size_t num );.

Upvotes: 0

user195488
user195488

Reputation:

According to the CERT Secure Coding Guidelines, you need to use pointers to const when referring to string literals.

So, char *str2 = "stack" needs to be const char *str2 = "stack";.

This will make it immutable.

Additionally, you are using deprecated/obsolete functions. The secure function you should be using is strcat_s. For example,

Compliant Example

enum { BUFFERSIZE=256 };

void complain(const char *msg) {
  static const char prefix[] = "Error: ";
  static const char suffix[] = "\n";
  char buf[BUFFERSIZE];

  strcpy_s(buf, BUFFERSIZE, prefix);
  strcat_s(buf, BUFFERSIZE, msg);
  strcat_s(buf, BUFFERSIZE, suffix);
  fputs(buf, stderr);
}

Read here about strcpy_s() and strcat_s().

Upvotes: 4

Related Questions