Home > Back-end >  Random number keep pop up inside my integer sorting algorithm
Random number keep pop up inside my integer sorting algorithm

Time:01-08

It work how he should do when the numbers are positive, but the negative number return 0. They is no error message when compiling or running. I use gcc compiler for window.

#include <stdio.h>

int main()
{
    int intergers[] = {4, 5, 1, -6, -7};
    int length = sizeof(intergers) / sizeof(intergers[0]);
    int c;
    int i1;
    int i2;

    for (int cursor = 1; cursor < length;   cursor)
    {
        c = cursor;
        while (true)
        {
            if(intergers[c] > intergers[c-1])
            {
                break;
            }
            i1 = intergers[c];
            i2 = intergers[c-1];
            intergers[c] = i2;
            intergers[c-1] = i1;
            --c;
        }
    
    }
    for (int cursor = 0; cursor < length;   cursor)
    {
        printf("%i ", intergers[cursor]);
    }
}

Output:

0 0 1 4 5

I try to use negative numbers in array for another context, it work just fine proof that I did something wrong in this code, but I cant found what.

CodePudding user response:

Your program has a stack buffer underflow (accessing integers[-1]), which causes undefined behavior:

gcc t.c -fsanitize=address && ./a.out

==134==ERROR: AddressSanitizer: stack-buffer-underflow on address 0x7ffc293bd81c at pc 0x000000401402 bp 0x7ffc293bd7d0 sp 0x7ffc293bd7c8
READ of size 4 at 0x7ffc293bd81c thread T0
    #0 0x401401 in main /tmp/t.c:16
    #1 0x7f2c26be7eaf in __libc_start_call_main (/lib64/libc.so.6 0x3feaf)
    #2 0x7f2c26be7f5f in __libc_start_main@GLIBC_2.2.5 (/lib64/libc.so.6 0x3ff5f)
    #3 0x4010d4 in _start (/tmp/a.out 0x4010d4)

Address 0x7ffc293bd81c is located in stack of thread T0 at offset 28 in frame
    #0 0x4011a5 in main /tmp/t.c:4

Changing while (true) to while (c > 0) fixes the bug.

  • Related