为两个连接的字符串分配内存

时间:2022-02-09 00:20:00

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)?

2 个解决方案

#1


3  

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(第一)+ strlen(第二)+ 1:

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

#2


2  

It should be

它应该是

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

allocating one more space (byte) for NUL terminator.

为NUL终结器分配一个空格(字节)。

#1


3  

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(第一)+ strlen(第二)+ 1:

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

#2


2  

It should be

它应该是

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

allocating one more space (byte) for NUL terminator.

为NUL终结器分配一个空格(字节)。