在 C 中的字符串数组中重新分配内存
我试图满足 valgrind 的要求并提出一个很好的实现,但我遇到了一个障碍。本质上我想做的就是将数组中的两个字符串减少为一个。假设 arr
包含
{ "One", "Two", "Three" }
并且每个字符串的内存分配已经完成(a la arr[1] = malloc(strlen("one") + 1) 和
strcpy(arr[1], "One")
进行一些字符串操作并尝试执行以下操作:
strcpy(arr[1],"OneTwo");
并删除 arr[2] 但这本质上是有问题的,因为 arr[1] 的内存分配已经改变。有件事告诉我,再次执行 malloc 会很糟糕。
我可以进行realloc,但这需要释放arr[2]并将其后的所有内容向下移动一个空间并重新分配。我也可以这样做 arr[2] = NULL
但 valgrind 不同意。
任何提示将不胜感激。
I'm trying to satisfy valgrind and come up with a nice implementation, but I'm coming across a snag. Essentially what I'm trying to do is reduce two strings in an array to one. Let's say arr
contains
{ "One", "Two", "Three" }
And that the memory allocation for each string has been done as it should be (a la arr[1] = malloc(strlen("one") + 1)
and strcpy(arr[1], "One")
.
I do some string manipulation and try to do:
strcpy(arr[1],"OneTwo");
and remove arr[2] but this is inherently problematic because the memory allocation for arr[1] has changed. Something tells me that doing malloc again would be bad.
I could do realloc
but that would require either freeing arr[2] and shifting everything after it down one space and realloc'ing. I could also do arr[2] = NULL
but valgrind disagrees.
Any hints would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
重新分配
arr[1]
并将arr[2]
附加到字符串末尾,然后释放arr[2]
(并设置arr[ 2] = NULL 以避免稍后混淆)。reallocate
arr[1]
and appendarr[2]
to the end of the string, then freearr[2]
(and set arr[2] = NULL to avoid confusion later).为什么
realloc
ingarr[1]
需要对其他内容进行任何修改?我觉得不错。这里的
arr[2]
之后没有任何内容,因此无需进行任何转换。如果有,那么是的,从任何数组的中间删除都要求您向下移动以下元素。Why would
realloc
ingarr[1]
require any modification of anything else?Looks good to me. There's nothing after
arr[2]
here so no shifting to do. If there were, then yes, removing from the middle of any array demands that you shift down the following elements.