gpt4 book ai didi

c - Malloc 函数无法正常工作

转载 作者:行者123 更新时间:2023-11-30 20:35:13 26 4
gpt4 key购买 nike

我在使用 malloc() 时遇到问题,不知道发生了什么。我正在使用 MinGW 进行编译。

Cadena 只是 char *typedef,而 leer_dato() 是一个返回字符串的函数。

Cadena leer_con_formato(const char * formato)
{
int i = 0;
Cadena dato = leer_dato();
if (strlen(dato) != strlen(formato))
return NULL;
char * nuevo_dato = (char *)malloc(strlen(dato)); // Here's the problem
if (!nuevo_dato)
return NULL;
while (dato[i] != '\0')
{
switch (formato[i])
{
case '0':
if (!isdigit(dato[i]))
return NULL;
nuevo_dato[i] = dato[i];
i++;
break;
case 'C':
if (!isalpha(dato[i]))
return NULL;
nuevo_dato[i] = dato[i];
i++;
break;
case 33 ... 47:
case 58 ... 64:
case 91 ... 96:
case 123 ... 126:
if (!ispunct(dato[i]))
return NULL;
nuevo_dato[i] = dato[i];
i++;
break;
default:
return NULL;
}
}
nuevo_dato[i] = NULO;
return nuevo_dato;
}

最佳答案

您没有分配足够的内存。如果 strlen 返回例如 5,则意味着您的字符串包含 5 个字符 + 1 作为终止 0 字节。因此,在为字符串分配内存时,您必须这样做:

char * nuevo_dato = (char*)malloc(sizeof(char) * (strlen(dato) + 1));

sizeof(char) 是可选的。

关于c - Malloc 函数无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40076022/

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