Home > Net >  why -fsanitizer=address gives me an error while making two dimensional array using malloc?
why -fsanitizer=address gives me an error while making two dimensional array using malloc?

Time:09-11

I was trying to make a to dimensional array using malloc But when I tried compiling the file using ' gcc *.c -g -fsanitize=address (file_name)' this shows me an error of

0x604000000cfb is located 0 bytes to the right of 43-byte region [0x604000000cd0,0x604000000cfb)
allocated by thread T0 here:
    #0 0x10ab6b17d in wrap_malloc 0x9d 

(libclang_rt.asan_osx_dynamic.dylib:x86_64h 0x4917d)

   #1 0x10ab0f64f in set_space make_database.c:60

   #2 0x10ab10750 in main rush.c:78

   #3 0x7fff695b2cc8 in start 0x0 (libdyld.dylib:x86_64 0x1acc8)

SUMMARY: AddressSanitizer: heap-buffer-overflow make_database.c:81 in store_line
Shadow bytes around the buggy address:

the #1 line points '*arr = (char *)malloc(sizeof(char) * (each_len[i] 1))

But I think there is no error in my code. Can you help me??

// total_line is 41
    arr = malloc(sizeof(char *) * (total_line   1));
    while (i < total_line)
    {   
// each_len is an integer array that stores length of each line.
        *arr = (char *)malloc(sizeof(char) * (each_len[i]   1));
        i  ;
        arr  ;
    }
    *arr = malloc(sizeof(char) * 2);
'''

CodePudding user response:

In this while loop ( I assume that the variable i was set to 0 before the loop)

while (i < total_line)
{   
    // each_len is an integer array that stores length of each line.
    *arr = (char *)malloc(sizeof(char) * (each_len[i]   1));
    i  ;
    arr  ;
}

the pointer arr is changed, which initially pointed to the allocated array of pointers.

Instead you could write

while (i < total_line)
{   
    // each_len is an integer array that stores length of each line.
    arr[i] = (char *)malloc(sizeof(char) * (each_len[i]   1));
    i  ;
}

arr[i] = malloc(sizeof(char) * 2);

Pay attention to that the array each_len shall contain initialized elements no less than total_line.

  • Related