-1

When I have a string of unknown size and I create an char array to hold this string.

I do something like this:

 #define LINE_END "\r\n"

int line_end_size = strlen(LINE_END);
char line[]="Hello! world.";
int line_size=strlen(line);
int test_line_size=line_size+line_end_size;
char *test_line = malloc(test_line_size);
strcpy(test_line,line);
strcat(test_line,LINE_END);

printf("test_line = ");
int index;
for (index = 0; index<test_line_size+1; index++) /* plus 1 to see the null */
    printf("%02X ", (unsigned char)test_line[index]);
printf("\n");

Should I add 1 to the size of test_line_size to hold the NULL character?

This must be compiled for linux32, win32, arm32.

closed as off-topic by Bart van Ingen Schenau, Ixrec, Adam Zuckerman, user22815, gnat Apr 19 '16 at 6:49

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions asking for assistance in writing or debugging existing code are off-topic on Programmers. These questions can be asked on Stack Overflow if they include the desired behavior, a specific problem or error, and the shortest code necessary to reproduce it in the question itself. See How To Create a Minimal, Complete, and Verifiable Example." – Ixrec, Community, gnat
If this question can be reworded to fit the rules in the help center, please edit the question.

  • Ask yourself what will happen if you don't add room for that zero. – Zan Lynx Apr 15 '16 at 17:41
  • 1
    Would also like to point out that whenever you know the length of a C string you should be using the "mem*" functions instead. Like memcpy(). The "str*" functions are a waste of time, looking for the zero terminator when you already know the length. – Zan Lynx Apr 15 '16 at 17:43
  • oh, okay. I will read... – jc__ Apr 15 '16 at 19:46
  • If I dont have the null the str functions will not know where the array ends... So 'I' must make room for it... – jc__ Apr 15 '16 at 19:48
0

If you treat it as a char array, then you don't need a 0 at the end. It's just an array like any other.

But if you want to use string functions on it (like the strcpy, strcat in your example), those will look for, rsp. add a null terminator at the end of your arrays, so you will need the reserved space for it!

Note that your strcat already writes this 0 past the end of the malloc'd space.

If you used the mem... functions (like @zan-lynx commented), and iterated the array without the +1, it'd be perfectly fine (if unusual).

Not the answer you're looking for? Browse other questions tagged or ask your own question.