[英]Malloc function doesn´t work properly
I'm getting a problem whit malloc()
, don't know what's happening.我遇到了
malloc()
问题,不知道发生了什么。 I'm compiling with MinGW.我正在使用 MinGW 进行编译。
Cadena is just a typedef
for char *
, and leer_dato()
is a function that returns a string. 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;
}
You are not allocating enough memory.您没有分配足够的内存。 If
strlen
returns for example 5 , then that means that your string contains 5 chars + 1 for the terminating 0-byte.如果
strlen
返回例如5 ,则意味着您的字符串包含 5 个字符+ 1 个用于终止 0 字节。 So when allocating memory for a string you'll have to do it like so:因此,在为字符串分配内存时,您必须这样做:
char * nuevo_dato = (char*)malloc(sizeof(char) * (strlen(dato) + 1));
The sizeof(char)
is optional. sizeof(char)
是可选的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.