Reputation:
it is not clear if + 1
is needed or not here:
int len = strlen(TARGET);
info = malloc( len + 1 );
because few lines above it it already was once appended to it:
TARGET[END - START] = '\0';
if it is needed then perhaps also.. appending the \0
is needed.
int len = strlen(TARGET);
info = malloc( len + 1 );
strcpy(info, TARGET);
info[len] = '\0';
Q: How to determine if a string already has the
null termination
perhaps if it already has it.. appending another one wouldn't be logic.
full function :
char * FUNCTION ( char * v ){
char *TARGET = NULL;
const char *PATTERN1 = "co=";
const char *PATTERN2 = "&";
char *START = strstr(v, PATTERN1);
if (START) {
START = START + strlen(PATTERN1);
char *END = strstr(START, PATTERN2);
if (!END){
END = START + strlen(START);
}
TARGET = malloc(END - START + 1);
memcpy(TARGET, START, END - START);
TARGET[END - START] = '\0';
}
if (!START || TARGET == NULL || TARGET[0] == '\0') {
return 0;
}
int len = strlen(TARGET);
info = malloc( len + 1 );
strcpy(info, TARGET);
info[len] = '\0';
return info;
}
Upvotes: 1
Views: 75
Reputation: 27139
strlen
calculates how many characters there are in a string up to and excluding the \0
, so you'll never count it. So for example if you string is "hello"
, its strlen
would be 5. So yes, you'll always need to add 1 to its length to account for the \0
at the end.
Upvotes: 3
Reputation: 134386
How to determine if a string already has the null termination
Well, a "string", is by definition, null-terminated. Otherwise, it is not a string.
Quoting C11
, chapter §7.1.1
A string is a contiguous sequence of characters terminated by and including the first null character. [....]
From theoretical point of view, it's the responsibility of the producer, not the consumer, to ensure the null-termination for a character array which is supposed to be used as string.
That said, strlen()
returns the length of a string, without the null-terminator. So, if you were to use the return value of strlen()
of an existing string to allocate memory for a copy thereof, you need to allocate one extra bye for the null-terminator, so the +1
is required while passing the size to allocator function.
Upvotes: 5
Reputation: 62120
The following:
int len = strlen(TARGET);
will not give you sizeof(TARGET)
; it will just count the number of characters before the first \0
. So, if TARGET
contains "a\0bcd"
it will give you just 1 (for 'a'
).
The following:
info = malloc( len +1 );
Needs to allocate enough bytes for the string plus the null terminator, so the + 1
is necessary.
The following:
strcpy(info, TARGET);
will copy characters until the first '\0'
is encountered, and then it will append a '\0'
, so there must be enough space in the destination for the '\0'
.
Upvotes: 1