gpt4 book ai didi

c - 该函数仅适用于无用的 printf

转载 作者:行者123 更新时间:2023-12-01 12:11:50 30 4
gpt4 key购买 nike

我通常会越来越努力地解决我在代码中发现的任何错误,但这对我来说完全不合逻辑。它适用于任何字符串和字符分隔符,但仅适用于无用的 printfwhile的函数,否则打印

-> Lorem

然后
-> ▼

并随后崩溃。在此先感谢任何可以告诉我发生了什么的人。
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdint.h>

char **strsep_(char *str, char ch) {
// Sub-string length
uint8_t len = 0;
// The number of sub-strings found means the same as the position where it will be stored in the main pointer
// Obviously, the number tends to increase over time, and at the end of the algorithm, it means the main pointer length too
uint8_t pos = 0;
// Storage for any found sub-strings and one more byte as the pointer is null-terminated
char **arr = (char**)malloc(sizeof(char **) + 1);
while (*str) {
printf("Erase me and it will not work! :)\n");
if (*str == ch) {
// The allocated memory should be one step ahead of the current usage
arr = realloc(arr, sizeof(char **) * pos + 1);
// Allocates enough memory in the current main pointer position and the '\0' byte
arr[pos] = malloc(sizeof(char *) * len + 1);
// Copies the sub-string size (based in the length number) into the previously allocated space
memcpy(arr[pos], (str - len), len);
// `-_("")_-k
arr[pos][len] = '\0';
len = 0;
pos++;
} else {
len++;
}
*str++;
}
// Is not needed to reallocate additional memory if no separator character was found
if (pos > 0) arr = realloc(arr, sizeof(char **) * pos + 1);
// The last chunk of characters after the last separator character is properly allocated
arr[pos] = malloc(sizeof(char *) * len + 1);
memcpy(arr[pos], (str - len), len);
// To prevent undefined behavior while iterating over the pointer
arr[++pos] = NULL;

return arr;
}

void strsep_free_(char **arr) {
char **aux = arr;
while (*arr) {
free(*arr);
*arr = NULL;
arr++;
}
// One more time to fully deallocate the null-terminated pointer
free(*arr);
*arr = NULL;
arr++;
// Clearing The pointer itself
free(aux);
aux = NULL;
}

int main(void) {
char **s = strsep_("Lorem ipsum four words", ' ');
char **i = s;
while (*i != NULL) {
printf("-> %s\n", *i);
i++;
}
strsep_free_(s);
}

最佳答案

崩溃的可能原因很可能是这样的:realloc(arr, sizeof(char **) * pos + 1) .

这与 realloc(arr, (sizeof(char **) * pos) + 1) 相同它没有为您的“数组”分配足够的空间。您需要做的realloc(arr, sizeof(char **) * (pos + 1)) .

arr[pos] 的分配相同,您也需要在那里正确使用括号。

关于c - 该函数仅适用于无用的 printf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51239712/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com