user14677223
user14677223

Reputation:

What is causing the segmentation fault?

I've having a segmentation fault error in my program. This is the code: for first, I've a struct:

struct Slave
{
    char **all_samples;
    int number_of_samples;
    char **last_samples;
    int **RSSI;
    int *AGC;
    int *AUTH;
};

Then I've a function: (debbugging I'm sure that the segmentation fault occurs when I call RSSI function). all_samples and last_samples are 2 arrays. the first contains N string (N is variable), while the second surely contains 4 strings.

struct Slave *read_slaves_file(char *file_path, char *slave)
{

    ...
    char **all_samples = malloc(N * sizeof(char *));
    char **last_samples = malloc(4 * sizeof(char *));


    struct Slave *slave_ptr = malloc(sizeof(struct Slave *));

    slave_ptr->last_samples = last_samples;
    slave_ptr->all_samples = all_samples;
    slave_ptr->number_of_samples = i;
 
    slave_ptr->RSSI = RSSI(slave_ptr->last_samples);


    return slave_ptr;
}

and this is RSSI function: it simply parse a string to extract the number after the -RSSI word. For example:

2022-10-14 8:51:17:708 -IP 192.168.101.11 -RSSI 88367 -AGC 429496720 -AUTH 0

It extracts 88367. It works on 4 strings like this one.

int **RSSI(char **last_samples)
{

    int **rssi_value = malloc(sizeof(int *) * 128);
    char string[128];

    const char s[16] = " ";
    char *token;
    int i;
    for (int k = 0; k < 4; k++)
    {
        strcpy(string, last_samples[k]);
        token = strtok(string, s);

        i = 0;
        while (token != NULL)
        {
            if (i == 5)
            {
                rssi_value[k] = atoi(token);
            }
            i++;
            token = strtok(NULL, s);
        }
    }


    return rssi_value;
}

Into main.c:

#include "lib.h"

int main()
{

    while (true)
    {

       ...
 
        struct Slave *slave_1 = read_slaves_file(FILE_PATH, SLAVE_1);

        free(slave_1->last_samples);
        free(slave_1->all_samples);
        free(slave_1->RSSI);
        free(slave_1);
    
        usleep(1000*1000);

    }
            return 0;
}

Upvotes: 0

Views: 43

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310910

This memory allocation is already invalid

struct Slave *slave_ptr = malloc(sizeof(struct Slave *));
                                        ^^^^^^^^^^^^^^   

You need to write

struct Slave *slave_ptr = malloc(sizeof(struct Slave));
                                        ^^^^^^^^^^^^^^   

or

struct Slave *slave_ptr = malloc(sizeof( *slave_ptr ));
                                        ^^^^^^^^^^^^^   

Also in this for loop

for (int k = 0; k < 4; k++)
{
    strcpy(string, last_samples[k]);
    //...

the call of strcpy uses uninitialized pointers last_samples[k].

And this statement

rssi_value[k] = atoi(token);

is also incorrect. There is an attempt to initialize a pointer with an integer.

Upvotes: 1

Related Questions