Reputation: 13931
I want to check C string length and if it is valid (\0
termination).
So far I have this:
#include <stdio.h>
char good_str[32] = "123456789012345"; // 15 chars with `\0` is ok
char bad_str[32] = "1234567890123456"; // 16 chars with `\0` is too long
int check_max_len(char * s, int max_len){
for (int i = 0; i < max_len; i++) {
if (s[i] == 0)
return 0; // not too long
}
return 1; // too long or no `\0`
}
int main() {
int is_bad;
is_bad = check_max_len((char*)&good_str, 16);
printf("Good string: %i\n", is_bad);
is_bad = check_max_len((char*)&bad_str, 16);
printf("Bad string: %i\n", is_bad);
return 0;
}
I guess this will work well for my application, but maybe there are some "industry standards", or some function in standard library for that?
Upvotes: 0
Views: 275
Reputation: 44
There is a standard function strnlen()
from the string.h
header file which comes fairly close to functionality you are looking for. It takes 2 parameters: a string
(const char*) and a maximum read length
(size_t) respectively.
It looks like this:
size_t strnlen(const char* str, size_t max_len);
It will return the quantity of bytes pointed to by the passed string, excluding the terminating null character if encountered within the the passed max_len
.
Logically speaking, this function still requires you to know the expected string length so that way you can have an accurate results. Without that information, your program will error out or it will do unexpected things such as reading into other strings, and data. Hence why you should make it clear that you expect null terminated strings to begin with.
Upvotes: 0