提问人:Meteorite 提问时间:12/26/2022 最后编辑:ZarakshRMeteorite 更新时间:12/26/2022 访问量:236
解除分配内存的分段错误 [已关闭]
Segmentation Fault to Deallocate the Memory [closed]
问:
由于以下代码中的 free() 函数,我收到了分段错误 (Segfault)。
如何在不收到分段错误的情况下在此代码中使用 free() 函数?
#include <iostream>
#include <cstring>
using namespace std;
void driver_01(int* buf1, int buf1_size) {
int* buf2 = (int*)malloc(buf1_size);
//int* buf2 = new int(buf1_size);
memcpy(&buf2, &buf1, buf1_size);
int count = 0;
for (int i = 0; i < buf1_size; i++) {
if (*(buf2 + i) != 0) {
count++;
}
cout << *(buf2 + i) << endl;
}
cout << "Size of buf2: " << count << endl;
free(buf2);
}
int main() {
int buf1[8] = { 2, 6, 12, 15, 22, 30, 40, 50 };
int buf1_size = sizeof(buf1) / sizeof(buf1[0]);
cout << "Size of buf1: " << buf1_size << endl;
driver_01(buf1, buf1_size);
return 0;
}
输出:
Size of buf1: 8
2
6
12
15
22
30
40
50
Size of buf2: 8
Segmentation fault
答:
1赞
pm100
12/26/2022
#1
你的实际问题就在这里
memcpy(&buf2, &buf1, buf1_size);
你是说
memcpy(buf2, buf1, buf1_size);
但正如其他人所说,你不能在 C++ 中使用 malloc 或 free,你应该使用 new 和 delete。但是在这个 caese 中,您应该使用 std::vector
编辑。你的 malloc 也错了(感谢 Remy)。你需要
malloc(sizeof(int) * buf1_size)
评论
0赞
Remy Lebeau
12/26/2022
这不是唯一的问题。这也是错误的。memcpy()
malloc()
0赞
pm100
12/26/2022
@RemyLebeau,我错过了
2赞
Remy Lebeau
12/26/2022
#2
你对 和 的使用都是错误的。malloc()
memcpy()
您没有为数组分配足够的内存来复制数组中的值。您只为 8 个字节分配空间,而不是 8 秒。
buf2
buf1
int
您从错误的源内存地址(参数本身的地址,而不是它指向的数组的地址)复制 8 个字节,而不是 8 秒,并将它们写入错误的目标内存地址(变量本身的地址,而不是它指向的数组的地址),因此您正在损坏内存。
int
buf1
buf2
请尝试以下操作:
void driver_01(int* buf1, int buf1_size) {
int* buf2 = (int*) malloc(sizeof(int) * buf1_size);
//int* buf2 = new int[buf1_size];
memcpy(buf2, buf1, sizeof(int) * buf1_size);
//std::copy_n(buf1, buf1_size, buf2);
int count = 0;
for (int i = 0; i < buf1_size; i++) {
if (buf2[i] != 0) {
++count;
}
cout << buf2[i] << endl;
}
/*
int count = count_if(buf2, buf2 + buf1_size,
[](int i){ return i != 0; });
for_each(buf2, buf2 + buf1_size,
[](int i){ cout << i << endl; });
*/
cout << "Size of buf2: " << count << endl;
free(buf2);
//delete[] buf2;
}
评论
malloc
free
new
delete
std::vector
malloc
free
malloc
free
malloc
free
malloc
free
memcpy
buf1_size
buf1
buf2