Home > Enterprise >  Where am I going out of bounds?
Where am I going out of bounds?

Time:02-21

My code takes in a series of words as command line arguments and should sort them using qsort. Right now I print out the original Args however when it goes to print the Sorted args I receive a segmentation error. New to C, all advice is appreciated.

#include <stdlib.h>
#include <string.h>


int stringCmp(const void *str1, const void *str2); //Function prototype.

int main (int argc, char *argv[])
{
  int i;
  char **arr = malloc(argc * sizeof(char *));
  printf("Original Args:\n");
  for (i = 0; i < argc-1; i  ){
    arr[i] = argv[i 1];
    printf("%s\n",arr[i]);
  }

  qsort(arr, argc, sizeof *arr, stringCmp);

  printf("\nSorted Args:\n");
  for (i = 0; i < argc; i  ){
    printf("%s\n", arr[i]);
  }
  free (arr);
  return 0;
}

int stringCmp(const void *str1, const void *str2)
{
  strcmp(str1, str2);
}

CodePudding user response:

Your comparison function isn't returning anything. Also, this function takes the address of the array elements, so what you're actually getting are char * const *, not void *

You want:

int stringCmp(const void *str1, const void *str2)
{
  const char * const *s1 = str1;
  const char * const *s2 = str2;
  return strcmp(*s1, *s2);
}

You're also not passing in the correct number of elements to qsort. It should be argc-1, not argc. The same going for printing the list:

  qsort(arr, argc-1, sizeof *arr, stringCmp);

  printf("\nSorted Args:\n");
  for (i = 0; i < argc-1; i  ){
    printf("%s\n", arr[i]);
  }

CodePudding user response:

For starters you are passing invalid number of elements

qsort(arr, argc, sizeof *arr, stringCmp);

You need to write

qsort(arr, argc - 1, sizeof *arr, stringCmp);

Secondly the function stringCmp returns nothing and uses incorrect arguments in the call of strcmp. It should look like

int stringCmp(const void *str1, const void *str2)
{
  return strcmp( *( const char ** )str1, *( const char ** )str2);
}

CodePudding user response:

out by one here too

for (i = 0; i < argc; i  ) {
    printf("%s\n", arr[i]);
}

should be

for (i = 0; i < argc - 1; i  ) {
    printf("%s\n", arr[i]);
}
  • Related