cheroky
cheroky

Reputation: 757

Strange characters when choosing names at random

I have the following code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

typedef struct persona
{
    char *nombre;
    int edad;
    int sexo;
} Persona;

typedef struct
{
    int size;
    Persona vecPersona[];
} Array;

Array* getArrayInstance()
{
    Array *vec;
    vec = (Array*) malloc (sizeof(Persona));
    vec->size = 0;
    return vec;
}

void push_back(Array ** vec, Persona tipito)
{
    (*vec)->vecPersona[(*vec)->size] = tipito;
    (*vec)->size++;
    printf("%d-", (*vec)->size);
    int newSize = (*vec)->size*2-(*vec)->size+1;
    Array *tmp = realloc((*vec), newSize*sizeof(Persona));
    if(tmp)
        *vec = tmp;
    else
        (*vec)->size--;
}

void mostrarPersonas(Array *vec)
{
    int i;
    printf("\n\n");
    printf("%d", vec->size);
    for(i=0; i<vec->size; i++)
    {
        printf("(%d) Nombre: %s - Edad: %d - Sexo: ", i, vec->vecPersona[i].nombre, vec->vecPersona[i].edad);
        if(vec->vecPersona[i].sexo == 0)
            printf("Masculino");
        else
            printf("Femenino");
        printf("\n");
    }
}

void cargarPersonas(Array **vec)
{
    int i, edad, random;
    int cantPersonas = 3;
    Persona aux;
    char hombres[][20] = {"Ramiro","Pedro","Federico","Jose","Antonio","Pablo","Raul","Gustavo","Gonzalo","Airton"};
    char mujeres[][20] = {"Mariana","Jennifer","Luz","Roxana","Ana","Sol","Micaela","Romina","Melina","Camila"};
    for(i=0; i<cantPersonas; i++)
    {
        edad = rand()%80+1;
        aux.edad = edad;
        if( (random = rand()%10) %2 == 0) 
        {
            aux.nombre = hombres[random];
            aux.sexo = 0;
        }
        else
        {
            aux.nombre = mujeres[random];
            aux.sexo = 1;
        }

        push_back(vec, aux);
    }

}


int main()
{
    srand(time(NULL));
    Array *vecPersonas = getArrayInstance();

    cargarPersonas(&vecPersonas); 
    printf("%d", vecPersonas->size);
    mostrarPersonas(vecPersonas);

    return 0;
}

The code compiles without errors, but it gives me problems when I execute it. For example I get strange characters in the name field.

Sample output:

<0> Nombre: ?ç!:. - Edad: 25 - Sexo: Maculino

Update

Apparently the problem is in the function push_back

void push_back(Array ** vec, Persona tipito)
{
    (*vec)->vecPersona[(*vec)->size] = tipito;
    (*vec)->size++;

    int newSize =  (*vec)->size + 1;
    Array *tmp = realloc(*vec, (newSize*sizeof(Persona))); // here

    if (!tmp)
    {
        printf("Cannot allocate more memory.\n");
        (*vec)->size--;
    }
    else
        *vec = tmp;
}

Upvotes: 1

Views: 99

Answers (1)

4pie0
4pie0

Reputation: 29744

First error:

Array* getArrayInstance()
{
    Array *vec;
    vec = (Array*) malloc (sizeof(Persona));
//                               ^^^^^^^^^
//                    should be sizeof(*vec) == sizeof(Array)    
    vec->size = 0;
    return vec;
}

Second error:

void push_back(Array ** vec, Persona tipito)
{
    (*vec)->vecPersona[(*vec)->size] = tipito;
//                            ^^^^^^
//                      access out of range
//                      the last object in array is indexed with size-1
//                      if you wanted the first object, which is indexed with 0
//                      then it is still wrong as your vec->size is 0 when there 
//                      is no memory allocated for the array

Strange characters in the stdout are the prophet of UB or more precisely a projection into our dimension of what has left behind it.

We, programmers, should avoid strange characters in the output at any cost. Whenever you see them take immediate action of correcting the fault program by paying attention to the code lines related to accessing array elements in particular but not limited to.

Upvotes: 5

Related Questions