简体   繁体   English

为两个串联的字符串分配内存

[英]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) ? 还是应该使用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 ) 一个尾随NUL字节( '\\0'或仅0

That makes it strlen(first) + strlen(second) + 1 : 这使其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. NUL终止符再分配一个空间(字节)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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