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

int comp(const void *a, const void *b) {
   const char *ia = (const char*)a;
   const char *ib = (const char*)b;
   return (*ia - *ib);
}



int main(int argc, char *argv[]){
   char *temp1 = "hello";
   char temp[] = "hello";

   qsort(temp, strlen(temp), sizeof(char), comp);
   printf ("%s\n", temp);

/*
   qsort(temp1, strlen(temp1), sizeof(char), comp);
   printf ("%s\n", temp1); 
*/
}

In this qsort call to sort a string, the code shown here works as shown (I mean it sorts the string "hello"). But when I uncomment the commented out last 2 lines (thereby sorting temp1), it crashes on mac pro with a bus error. The version information on cc shows:

Apple LLVM version 10.0.0 (clang-1000.10.44.4) Target: x86_64-apple-darwin17.7.0 Thread model: posix

I'm wondering why it produces bus error.

Krishna Kanth Yenumula
  • 2,533
  • 2
  • 14
  • 26
coder
  • 11
  • 2
  • Maybe the problem is that in the method qsort() the first argument is array of char or string, but you are passing a reference. Try passing *temp1,ie using asterisk again, which again changes reference into object – hemant kumar Dec 25 '20 at 04:51
  • See [Initializing a char pointer in C. Why considered dangerous?](https://stackoverflow.com/questions/8795576/initializing-a-char-pointer-in-c-why-considered-dangerous). The defensive/safe programming answer to your question is that you should have explicitly declared `temp1` as pointer to `const` i.e. `const char *temp1 = "hello";` which would have caused the `const` violation to be caught at compile time. – dxiv Dec 25 '20 at 04:58

1 Answers1

4
char *temp1 = "hello"; // pointer to a const string

temp1 points to a string literal. You cannot modify it. qsort() function tries to modify it. That is the reason for error.

char temp[] = "hello"; //const pointer to a string

Here, the array contents can be modified. That's why it works.

Krishna Kanth Yenumula
  • 2,533
  • 2
  • 14
  • 26