Home > Blockchain >  Sigabrt when iterating an array pointer in C
Sigabrt when iterating an array pointer in C

Time:03-05

I wrote this C code to add a list of Fibonacci numbers dynamically to an array. The calculation and assignment works just fine. but when trying to print the values i am getting a segment fault error.

int main(int argc, char **argv) {

    int num;
    int* nums; 

    scanf("%d", &num);
    nums = (int *) calloc(num, sizeof(int));
    nums[0] = 0;
    nums[1] = 1;
    for (int i = 2; i <= num; i  ) {
        nums[i] = nums[i - 2]    nums[i - 1];   
    }

    
    for (int i = 0; i < num; i  ) {
        printf(" %d ", nums[i]); //seg fault here (line 19 of main.c)
    }

    return 0;
}

Backtrace from GDB

#0  __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:49
#1  0x00007ffff7de4864 in __GI_abort () at abort.c:79
#2  0x00007ffff7e5020a in __malloc_assert (
    assertion=assertion@entry=0x7ffff7f6f338 "(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)", file=file@entry=0x7ffff7f6acdf "malloc.c", line=line@entry=2539, function=function@entry=0x7ffff7f6fbd0 <__PRETTY_FUNCTION__.3> "sysmalloc") at malloc.c:303
#3  0x00007ffff7e52914 in sysmalloc (nb=nb@entry=1040, av=av@entry=0x7ffff7f9eba0 <main_arena>) at malloc.c:2539
#4  0x00007ffff7e5376f in _int_malloc (av=av@entry=0x7ffff7f9eba0 <main_arena>, bytes=bytes@entry=1024) at malloc.c:4366
#5  0x00007ffff7e551a4 in __GI___libc_malloc (bytes=bytes@entry=1024) at malloc.c:3229
#6  0x00007ffff7e3c2d4 in __GI__IO_file_doallocate (fp=0x7ffff7f9f6c0 <_IO_2_1_stdout_>) at filedoalloc.c:101
#7  0x00007ffff7e4c030 in __GI__IO_doallocbuf (fp=fp@entry=0x7ffff7f9f6c0 <_IO_2_1_stdout_>) at libioP.h:948
#8  0x00007ffff7e4b0c0 in _IO_new_file_overflow (f=0x7ffff7f9f6c0 <_IO_2_1_stdout_>, ch=-1) at fileops.c:745
#9  0x00007ffff7e49815 in _IO_new_file_xsputn (n=1, data=<optimized out>, f=<optimized out>) at libioP.h:948
#10 _IO_new_file_xsputn (f=0x7ffff7f9f6c0 <_IO_2_1_stdout_>, data=<optimized out>, n=1) at fileops.c:1197
#11 0x00007ffff7e32406 in outstring_func (done=0, length=1, string=0x555555556007 " %d ", s=0x7ffff7f9f6c0 <_IO_2_1_stdout_>) at ../libio/libioP.h:948
#12 __vfprintf_internal (s=0x7ffff7f9f6c0 <_IO_2_1_stdout_>, format=0x555555556007 " %d ", ap=ap@entry=0x7fffffffdee0, mode_flags=mode_flags@entry=0) at vfprintf-internal.c:1404
#13 0x00007ffff7e1d70f in __printf (format=<optimized out>) at printf.c:33
#14 0x000055555555529c in main (argc=1, argv=0x7fffffffe0e8) at main.c:19

CodePudding user response:

The line:

 for (int i = 2; i <= num; i  ) {

has an off by one error. Change the <= to <. Gdb detected the error and used SIGABRT to terminate the process.

  • Related