Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C and gcc error array subscript is above array bounds [closed]

Tags:

c

I have a to deal with a structure of a lib :

typedef struct {
   uint8_t   response_type;
   uint8_t   error_code;
   uint16_t sequence;
   uint32_t resource_id;
   uint16_t minor_code;
   uint8_t major_code;
   uint8_t pad0;
   uint32_t pad[5];
   uint32_t full_sequence;
} a_structure;

my problem come from the pad[5] member of the structure that I don't really understand. I thougth this member can be used as the other member in function like that:

uint8_t get_response_type( a_structure * my_struct)
{
   return my_struct->response_type;
}

but this function:

uint32_t get_pad_5( a_structure * my_struct)
{
   return my_struct->pad[5];
}

generate warning in gcc

error array subscript is above array bounds

Can someone explain me what this means ?

Thxs

like image 646
cedlemo Avatar asked Oct 08 '12 15:10

cedlemo


Video Answer


2 Answers

Structure field pad was defined as "array of 5 uint32_t". You must differ variable definition from using the variable. So since pad is defined, pad[5] means "get the fifth (counting from 0) element of pad array". But there is no such element in pad array, because the highest index available for this array is 4.

Also, it seems that you want to return pointer to the first element of this array, not the fifth element. So you must rewrite your function this way:

uint32_t * get_pad_5( a_structure * my_struct)
{
    return my_struct->pad;
}
like image 101
ThomasMore Avatar answered Sep 30 '22 00:09

ThomasMore


When you crate an array with 5 members, they get indexed 0-4, if you try to acces 5, you're out of bounds

like image 35
Minion91 Avatar answered Sep 29 '22 23:09

Minion91