-2

I'm getting a problem whit malloc(), don't know what's happening. I'm compiling with MinGW.

Cadena is just a typedef for char *, and leer_dato() is a function that returns a string.

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;
}
Racil Hilan
  • 24,690
  • 13
  • 50
  • 55

1 Answers1

0

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. 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.

jule
  • 96
  • 3