且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

释放C结构体内部的char数组

更新时间:2022-04-02 21:55:02

在数组中分配字符串时,

When allocating the strings in the array,

malloc(sizeof(str))

仅为 char * ,而不是它指向的字符串(除非 str 是普通数组而不是指针)。相反,请尝试

only allocates enough space for a char *, rather than the the string it points to (unless str was an ordinary array rather than a pointer). Instead, try

malloc(strlen(str) + 1)

为字符串中的字符分配足够的空间以及一个终止的null。

to allocate enough room for the characters in the string plus a terminating null.