0

I am writing a basic qsort to sort an array of strings. What I have so far is:

int scmp(const void *p1, const void *p2)
{
    const char* s1 = p1;
    const char* s2 = p2;
    // ...
}

int main(void)
{
    char* strings[] = {"Onus", "deacon", "Alex", "zebra"};
    qsort(strings, sizeof(strings), sizeof(*strings), scmp);
}

Note that above the sizeof(strings) gives me 32 (4 pointers), whereas what I want is sizeof(strings)/sizeof(*strings). This fixes the issue, but I'm curious what the "stack smashing" means and how that occurs?

David542
  • 104,438
  • 178
  • 489
  • 842
  • 4
    Stack smashing just means that the code is writing to parts of the stack that it shouldn't. This occurs because `qsort` writes in the array you give it to do the sort. Since you told it there were more entries in the array than there really is it will write to places it shouldn't. – kaylum Mar 05 '21 at 05:49

1 Answers1

1

The strings pointer array is allocated on the stack. With your bug, you "lie" to qsort and tells it there's 32 char* there to sort, instead of 4. So it runs off outside the allocated array and accesses memory that you don't have access to.

What can happen then is undefined behavior. You could get a "seg fault" (SIGSEGV) or "access violation" for accessing invalid storage. You could silently corrupt stack data, leading to very strange bugs. In this case you got "stack smashing", which simply means that a stack corruption was detected. This happens when you overwrite the "stack canary"1), a fixed value set on the stack to warn primarily against stack overflows.


1) Named after the analogy of canary birds used in coal mines - in case of carbon monoxide poisoning, the canary would pass out first, so the miners would notice and make it to safety.

Lundin
  • 195,001
  • 40
  • 254
  • 396
  • (At some point I proposed that the Stack Overflow "tavern on the meta" chat should be named Stack Canary Twitter, but it was such an intricate nerdy joke that nobody got it...) – Lundin Mar 05 '21 at 13:58
  • @lunda -- thanks for this. Is "stack canary" something specific to the GCC compiler or is that part of the C standard? – David542 Mar 05 '21 at 19:40
  • 1
    @David542 The C standard doesn't even mention or require a stack. It's a trick that the specific compiler can setup as part of the C runtime that executes before main() launches. On embedded systems you can create something similar yourself by mapping the stack so that it overflows into memory where data accessing reads to an exception/interrupt. – Lundin Mar 07 '21 at 10:37