arrays - C code Error: free(): invalid next size (fast): -


i got error code, i'm not sure fix it.

here's explanation of code does:

i'm writing code read input file , store each line object (char type) in array. first line of input file number. number tells me how many lines should read , store in array. here's code:

int main(int argc, char *argv[]){     file *fp;      char **path;     int num, i;     ...     /*after reading first line , store number value in num*/     path = malloc(num *sizeof(char));     ...     free(path); } 

after running code, this

*** glibc detected *** free(): invalid next size (fast):  

i have searched around , know malloc/free error, don't know fix it. great. thanks!

path = malloc(num *sizeof(char)); 

this wrong. path pointer pointer char, need allocate num * sizeof(char*), not sizeof(char), 1 (but pointer not 1 byte).

to initialize pointer dynamically, allocate number of elements desired multiplied the size of type pointer points to. pointer points char*, not char. pointers points point chars (that's kind of fun say...)

to simplify:

some_ptr *p = malloc(num_elems * sizeof *p); 

the compiler knows how deal sizeof(*p) correctly, you're not dereferencing pointer (which otherwise invoke ub pointer uninitialized).


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -