Arraylist in C not working

前端 未结 4 729
旧时难觅i
旧时难觅i 2020-12-30 15:54

I am currently writing a program to implement an arraylist (or dynamic array) in C. Hmm... I think I have 70 - 80% done with it, however, I found a serious problem with my c

4条回答
  •  半阙折子戏
    2020-12-30 16:20

    In the arraylist_add method you are storing the address of a local variable new_data in to the list. This variable will destroyed as soon as the control comes out of the function. Hence you have invalid pointers which when derefrenced invoke undefined behavior. To fix this problem, you need to allocate memory for the string from heap using malloc i.e. you need to do something like value_type* new_data = (value_type*)malloc( (size + 1) * sizeof(value_type));. Also remember that you have to deallocate this memory yourself using free.

提交回复
热议问题