简体   繁体   中英

Allocating memory for two concatenated strings

Is this a right way to allocate memory in order to store two concatenated strings?

size_t len1 = strlen(first);
size_t len2 = strlen(second);

char * s = malloc(len1 + len2 + 2);

or should I use malloc(len1 + len2 + 1) ?

Let's look at what's necessary to store a string:

  • one byte per character (assuming non-wide chars)
  • one trailing NUL byte ( '\\0' , or just 0 )

That makes it strlen(first) + strlen(second) + 1 :

char *s = malloc(len1 + len2 + 1);

It should be

char * s = malloc(len1 + len2 + 1); // 1 more space for \0  

allocating one more space (byte) for NUL terminator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM