cpointerserror-detection

Segmentation Fault in Vertical Redundancy Check


I am trying to make program in C for vertical redundancy check. The Code is given below :

#include<stdio.h>
#include<sys/types.h>
#include<fcntl.h>
#include<unistd.h>

    int main()
    {
        int fd,i;
        char *data = "01010101010111110101010101011111";
        int count = 0,bit_count=0;
        char *parity_bit_array = NULL;
        char *data_to_send = NULL;
        char *stream_name = "Named Stream";
        do
        {
            if(*data == '1' && bit_count <= 8)
            {
                count++;
                if(bit_count == 8) 
                {
                        if( count % 2 == 0)
                        {
                            *parity_bit_array = '1';
                            count = 0;
                            bit_count = 0;
                        }
                        else
                        {
                            *parity_bit_array = '0';
                            count = 0;
                            bit_count = 0;
                        }
                }
            }
            bit_count++;
            data++;
        } while( !data);
        do
        {
            if(bit_count <= 8)
            {
                *data_to_send++ = *parity_bit_array++;
            }
            *data_to_send++ =  *data;
        } while( !data );
        printf("%s \n",data_to_send);
        mkfifo(stream_name,0666);
        fd = open(stream_name,O_WRONLY);
        write(fd,data_to_send,sizeof(data_to_send));
        close(fd);
        unlink(stream_name);
        return 0;
    }

The file shown below is the sender file of which data is to be read by the receiver. By using sized array it is working properly but i like to use it with Pointer. Main Variables in this code :

  1. data : Data on which VRC to be implemented
  2. count : Counting 1 for Even Parity Bit
  3. bit_count : Counting 8 Bits
  4. parity_bit_array : To Collect Parity Bit for Every Single Byte present in data
  5. data_to_send : Combination made by data + parity_bit_array

Ex: data : 01110000 parity_bit_array : 1 data_to_send : 011100001


Solution

  • You are not allocating memory for your char pointers and you are trying to write to them which will lead to undefined behavior hence segmentation fault.

     *parity_bit_array = '1';
    

    There are multiple such cases in this code.

     char *data_to_send = NULL;
    

    data_to_send pointer is never allocated memory and you try to write to it

    *data_to_send++ = *parity_bit_array++;
    

    Allocate memory to char pointers like

     char *data_to_send = malloc(20);
    

    While writing to this array if you see 20 bytes is already written just do realloc() for the same memory

    char *temp = realloc(data_to_send,40);
    if(temp != NULL)
    data_to_send = temp;