I have to make sure that a string passed as argument does not cause an overflow. I’m doing this by using strncpy, but the ending ‘\0’, allocating the right amount of memory and so on gives me some troubles…
My solution is this:
l = strlen(argv[optind]);
if(l<MAX_LENGTH) {
msg = malloc((l+1) * sizeof(char));
msg = strcpy(msg, argv[optind]);
} else {
msg = malloc((MAX_LENGTH+1) * sizeof(char));
msg = strncpy(msg, argv[optind], MAX_LENGTH);
msg[MAX_LENGTH+1] = '\0';
}
It works, but I’m wondering if it is really correct and if there is a more compact solution?
I think this is about the simplest you can get: