I am trying to create a program that receives from the user 12 song titles and then forms a set list in a random order. I have used the gets()
function and memory allocation so that the input is placed into an array like this:
argv[0] = song1, argv[1] = song2, argv[2] = song3 (etc.).
There seems to be the common segmentation fault error when inputting the actual songs and then running it through the randomize and createSetList()
functions. However, if one were to scrap the memory allocation and hard code instead it would work fine. By this I mean something like:
char *input[ SONG ] =
{ "song1", "song2", "song3", "song4",
"song5", "song6", "song7", "song8",
"song9", "song10", "song11", "song12", "song13" };
Although, my purpose is to have the user input the song titles during run time. What is the reason for a segmentation fault error?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define SONG 13
#define SETSIZE 5
// prototypes
void randomize( unsigned int wDeck[ SONG ] );
void createSetList( unsigned int wDeck[ SONG ], char *wFace[] );
int main( void ){
printf("Please enter the songs you want to play!\n");
printf("I will create the set list and randomize it for you!\n");
char input[100];
char *argv[ SONG ];
char *token;
/*memory allocation for inputting song titles into a single array*/
/*****memory allocation code starts here********/
gets(input);
token = strtok(input, " ");
int i=0;
while( token != NULL ) {
argv[i] = malloc(strlen(token) + 1);
strncpy(argv[i], token, strlen(token));
i++;
token = strtok(NULL, " ");
}
argv[i] = NULL; //argv ends with NULL
/***memory allocation code ends here*****/
unsigned int setList[ SONG ] = { 0 };
srand( time( NULL ) ); // seed random-number generator
randomize( setList ); // shuffle the list
createSetList( setList, argv ); // create the setlist
} //end of main
/*SHUFFLE FUNCTION*/
void randomize( unsigned int wDeck[ SONG ] ){
size_t column;
size_t c;
for ( c = 1; c <= SETSIZE; ++c ) {
do {
column = rand() % SONG;
} while( wDeck[ column ] != 0 );
wDeck[ column ] = c;}}
/* Create Set List Function */
void createSetList( unsigned int wDeck[ SONG ], char *wFace[] ){
size_t c;
size_t column;
for ( c = 1; c <= SETSIZE; ++c ) {
for ( column = 0; column < SONG; ++column ) {
if ( wDeck[ column ] == c ) {
printf( "%s\n", wFace[ column ]);
}}}}