Mallocing an unsigned char array to store ints

Posted by Max Desmond on Stack Overflow See other posts from Stack Overflow or by Max Desmond
Published on 2012-12-11T02:53:46Z Indexed on 2012/12/11 5:04 UTC
Read the original article Hit count: 163

I keep getting a segmentation fault when i test the following code. I am currently unable to find an answer after having searched the web.

a = (byte *)malloc(sizeof(byte) * x ) ; 

for( i = 0 ; i < x-1 ; i++ )
{
scanf("%d", &y ) ;
a[i] = y ;
}

Both y and x are initialized. X is the size of the array determined by the user. The segmentation fault is on the second to last integer to be added, i found this by adding printf("roar") ; before setting a[i] to y and entering one number at a time. Byte is a typedef of an unsigned char.

Note: I've also tried using

a[i] = (byte)y ;

A is ininitalized as follows

byte *a ;

If you need to view the entire code it is this:

#include <stdio.h>
#include <stdlib.h>
#include "sort.h"

int p_cmp_f () ;

int main( int argc, char *argv[] ) 
{
  int x, y, i, choice ;

  byte *a ;

  while( choice !=2 )
    {
      printf( "Would you like to sort integers?\n1. Yes\n2. No\n" ) ;

      scanf("%d", &choice ) ;

      switch(choice)
    {
    case 1:
      printf( "Enter the length of the array: " ) ;

  scanf( "%d", &x ) ;

  a =  (byte *)malloc(sizeof( byte ) * x ) ;

  printf( "Enter %d integers to add to the array: ", x ) ;

  for( i = 0 ; i < x -1 ; i++ )
    {
    scanf( "%d", &y ) ;

    a[i] = y ;
    }
  switch( choice )
    {
    case 1:
      bubble_sort( a, x, sizeof(int), p_cmp_f ) ;

      for( i = 0 ; i < x ; i++ )
    printf( "%d", a[i] ;


      break ;

    case 2:
      selection_sort( a, x, sizeof(int),  p_cmp_f ) ;

      for( i = 0 ; i < x; i++ )
    printf( "%d", a[i] ;


      break ;

    case 3:
      insertion_sort( a, x, sizeof(int), p_cmp_f ) ;

      for( i = 0 ; i < x ; i++ )
    printf( "%d", a[i] ;


      break ;

    case 4: 
      merge_sort( a, x, sizeof(int), p_cmp_f ) ;

      for( i = 0 ; i < x ; i++ )
    printf( "%d", a[i] ;

      break ;

    case 5:
      quick_sort( a, x, sizeof(int), p_cmp_f ) ;

      for( i = 0 ; i < x ; i++ )
    printf( "%d", a[i] ;


      break ;

    default:
      printf("Enter either 1,2,3,4, or 5" ) ;

      break ;
    }
    case 2:
      printf( "Thank you for using this program\n" ) ;

      return 0 ;

      break ;

    default: 
      printf( "Enter either 1 or 2: " ) ;

    break ;
    }
}
  free(a) ;

  return 0 ;
}

int p_cmp_f( byte *element1, byte *element2 )
{
  return *((int *)element1) - *((int *)element2) ;
}

© Stack Overflow or respective owner

Related posts about arrays

Related posts about char