Ad

Why Does The Array Contain Values Which I Did Not Specify?

- 1 answer

I'm trying to make a program which crosses binary numbers. The problem is with the cross function. It accepts two binary sequences and returns 5 sequences which are the result of crossing the arguments. Somewhy, the first of these sequences has a mess of values, and I cannot really solve this problem. Does anyone have any ideas?

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

#define BINARY_LEN 5
#define POPULATION 5
// #define CROSS_BINARY_LIMIT 3

unsigned randrange(unsigned lower, unsigned upper)
{
    return lower + rand() / (RAND_MAX / (upper - lower + 1) + 1);
}

unsigned char *int_to_bin(unsigned number)
{
    unsigned char *binary = malloc(BINARY_LEN);    
    
    unsigned count = 0;
    while (number > 0)
    {
        binary[count] = number % 2;        
        number /= 2;
        count++;
    }

    return binary;
}

unsigned char **cross(unsigned char *parent_1, unsigned char *parent_2)
{
    unsigned char **offspring = malloc(POPULATION);
    unsigned cross_binary_point;

    for (unsigned char i = 0; i < POPULATION; i++)
    {
        cross_binary_point = randrange(0, BINARY_LEN);
        offspring[i] = malloc(BINARY_LEN);

        for (unsigned char j = 0; j < BINARY_LEN; j++)
        {
            if (j < cross_binary_point)
            {
                offspring[i][j] = parent_1[j];
                
            }
            else
            {
                offspring[i][j] = parent_2[j];
            }            
        }
    }

    return offspring;
}    

int main(void)
{
    unsigned char *x = int_to_bin(14);
    unsigned char *y = int_to_bin(18);

    for (unsigned char i = BINARY_LEN; i > 0; i--)
    {
        printf("%hhu", x[i - 1]);
    }

    printf("\n");

    for (unsigned char i = BINARY_LEN; i > 0; i--)
    {
        printf("%hhu", y[i - 1]);
    }

    printf("\n\n");

    unsigned char **ofspr = cross(x, y);

    printf("%s\n", ofspr[0]); // Try to check out what's wrong with the first array

    for (unsigned char i = 0; i < POPULATION; i++)
    {        
        for (unsigned char j = BINARY_LEN; j > 0; j--)
        {
            printf("%hhu", ofspr[i][j]);
        }
        printf("\n");
    }

    free(ofspr);
    free(x);
    free(y);
}

The output is like this:

01110
10010

`w;
00059119
01011
01001
01111
01011

Maybe there is some memory conflict stuff, but I do not have any ideas

Ad

Answer

unsigned char **offspring = malloc(POPULATION);

only allocates 5 bytes, you want 5 pointers

should be

unsigned char **offspring = malloc(POPULATION * sizeof(char*));
Ad
source: stackoverflow.com
Ad