Home > Back-end >  Segmentation fault (core dumped) - part of the pointer is overwritten, how to solve it?
Segmentation fault (core dumped) - part of the pointer is overwritten, how to solve it?

Time:03-14

When debugging, I found out that part of the pointer I need is erased and this error is caused. But I don't understand why the "i" or "j" declaration does this...

My code

#include <stdio.h>
#include <stdbool.h>
#include <malloc.h>

typedef unsigned long bitset_index_t;

typedef struct
{
    bitset_index_t index;
    unsigned short *vyraz;

} bitset_t;

void bitset_alloc(bitset_t **pole, unsigned int velikost)
{
    if (velikost < 1)
    {
        // todo error
    }
    bitset_t new_bitset = {.index = 0, .vyraz = NULL};
    new_bitset.vyraz = malloc(sizeof(unsigned short) * velikost);
    if (new_bitset.vyraz == NULL)
    {
        // todo error
    }
    memset(new_bitset.vyraz, 0, sizeof(unsigned short) * (velikost));

    for (unsigned int i = 0; i < velikost;   i)
    {

        new_bitset.vyraz[i] = 0;
        new_bitset.index  ;
    }
    *pole = &new_bitset;
}

void Eratosthenes(bitset_t *pole)
{
    pole->vyraz[0] = 1;
    pole->vyraz[0] = 1;

    unsigned long velikost = pole->index;
    for (unsigned long i = 2; i < velikost; i  )
    {
        for (unsigned long j = i; j * i < velikost   1; j  )
        {
            if (pole->vyraz[i])
                break;
            pole->vyraz[i * j] = 1;
        }
    }
    unsigned short count_prvocisel = 0;
    for (unsigned long i = pole->index; i > 0; i--)
    {
        if (count_prvocisel < 10)
        {
            if (pole->vyraz[i])
                continue;
            printf("%lu ", i);
            count_prvocisel  ;
        }
        else
            break;
    }
}

int main()
{
    bitset_t *test = NULL;

    bitset_alloc(&test, 10);

    Eratosthenes(test);
}

this is the data before the first cycle enter image description here

this is at the time of the error enter image description here

CodePudding user response:

You have 'returned' the address of a local variable

void bitset_alloc(bitset_t** pole, unsigned int velikost)
{
    if (velikost < 1)
    {
        // todo error
    }
    bitset_t new_bitset = { .index = 0, .vyraz = NULL }; <<<<========
    new_bitset.vyraz = malloc(sizeof(unsigned short) * velikost);
    if (new_bitset.vyraz == NULL)
    {
        // todo error
    }
    memset(new_bitset.vyraz, 0, sizeof(unsigned short) * (velikost));

    for (unsigned int i = 0; i < velikost;   i)
    {

        new_bitset.vyraz[i] = 0;
        new_bitset.index  ;
    }
    *pole = &new_bitset; <<<<<=========

}

'new_bitset' is a local variable that will be released once this function exits, saving its value - effectively returning it - is invalid and results in UB.

Either malloc it too or create it in 'main'

  • Related