free char*: invalid next size (fast) [duplicate]

不羁的心 提交于 2019-11-26 16:49:26

Your code is wrong.

You are allocating space for a single pointer (malloc(sizeof(char*))), but no characters. You are overwriting your allocated space with all the strings, causing undefined behavior (in tihs particular case, corrupting malloc()'s book-keeping data).

You don't need to allocate space for the pointer (res), it's a local variable. You must allocate space for all the characters you wish to store at the address held by the pointer.

Since you're going to be traversing a list to find strings to concatenate, you can't know the total size upfront. You're going to have to do two passes over the list: one to sum the strlen() of each string, then allocate that plus space for the separator and terminator, then another pass when you actually do the concatenenation.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!