문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top