* @brief This function formats the content of a String object based on the provided format * string and additional arguments, similar to how printf works. The formatted result * is assigned to the input String object. If the input String object or format string * is NULL, the function logs an error and returns without making changes. * * @param str The String object to which the formatted
| 3198 | |
| 3199 | /** |
| 3200 | * @brief Duplicates up to `n` characters from a given string. |
| 3201 | * |
| 3202 | * This function creates a new string by duplicating the first `n` characters |
| 3203 | * from the input string `str`. If the length of `str` is less than `n`, the |
| 3204 | * entire string is duplicated. The resulting string is null-terminated. |
| 3205 | * |
| 3206 | * @param str The input string to duplicate. |
| 3207 | * @param n The maximum number of characters to duplicate from `str`. |
| 3208 | * |
| 3209 | * @return A pointer to the newly allocated string that contains the first `n` |
| 3210 | * characters from `str`. The string is null-terminated. If memory |
| 3211 | * allocation fails, the function returns `NULL`. |
| 3212 | * |
| 3213 | * @note The caller is responsible for freeing the memory allocated by this |
| 3214 | * function using `free()`. |
| 3215 | */ |
| 3216 | char* string_strndup(const char* str, size_t n) { |
| 3217 | STRING_LOG("[string_strndup]: Function start."); |
| 3218 | /* NULL-safety: strlen(NULL) is UB. */ |
| 3219 | if (!str) { |
| 3220 | STRING_LOG("[string_strndup]: Error - str is NULL."); |
| 3221 | return NULL; |
| 3222 | } |
| 3223 | |
| 3224 | /* Like POSIX strndup, never look past str[n - 1]: the source may be a |
| 3225 | slice of a buffer that is not NUL-terminated (strlen would overread). */ |
| 3226 | const char* nul = (const char*)memchr(str, '\0', n); |
| 3227 | size_t len = nul ? (size_t)(nul - str) : n; |
| 3228 | |
| 3229 | char* result = (char*)malloc(len + 1); |
| 3230 | if (!result) { |
| 3231 | STRING_LOG("[string_strndup]: Error - Memory allocation failed."); |
| 3232 | return NULL; |
| 3233 | } |
| 3234 | |
| 3235 | result[len] = '\0'; |
| 3236 | memcpy(result, str, len); |
| 3237 | STRING_LOG("[string_strndup]: Successfully duplicated %zu characters.", len); |
| 3238 | |
| 3239 | return result; |
| 3240 | } |
| 3241 | |
| 3242 | |
| 3243 | /** |
| 3244 | * @brief Checks if the given String object is a palindrome. |
| 3245 | * |
| 3246 | * This function verifies whether the input String object is a palindrome. |
nothing calls this directly
no test coverage detected