gpt4 book ai didi

c++ - Valgrind 无效读取大小 4 错误?

转载 作者:行者123 更新时间:2023-11-30 04:08:41 29 4
gpt4 key购买 nike

尝试释放列表后,我在 Valgrind 中遇到此错误。

这是Valgrind的重要部分

    ==12349== Invalid read of size 4
==12349== at 0x8048BB4: DynArray::addMovie(Movie*) (in /home/admin/a2/mbd)
==12349== by 0x8048D11: main (in /home/admin/a2/mbd)
==12349== Address 0x4321060 is 0 bytes after a block of size 0 alloc'd
==12349== at 0x402B454: operator new[](unsigned int) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==12349== by 0x8048B62: DynArray::DynArray() (in /home/admin/a2/mbd)
==12349== by 0x8048C87: main (in /home/admin/a2/mbd)
==12349==
==12349== Invalid read of size 4
==12349== at 0x8048BB4: DynArray::addMovie(Movie*) (in /home/admin/a2/mbd)
==12349== by 0x8048D97: main (in /home/admin/a2/mbd)
==12349== Address 0x4321114 is 0 bytes after a block of size 4 alloc'd
==12349== at 0x402B454: operator new[](unsigned int) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==12349== by 0x8048B90: DynArray::addMovie(Movie*) (in /home/admin/a2/mbd)
==12349== by 0x8048D11: main (in /home/admin/a2/mbd)
==12349==
==12349== Invalid read of size 4
==12349== at 0x8048BB4: DynArray::addMovie(Movie*) (in /home/admin/a2/mbd)
==12349== by 0x8048E1D: main (in /home/admin/a2/mbd)
==12349== Address 0x43211d0 is 0 bytes after a block of size 8 alloc'd
==12349== at 0x402B454: operator new[](unsigned int) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==12349== by 0x8048B90: DynArray::addMovie(Movie*) (in /home/admin/a2/mbd)
==12349== by 0x8048D97: main (in /home/admin/a2/mbd)

DynArray.cc重要部分

    DynArray::DynArray() {
size = 0;
array = new Movie *[size];
}

void DynArray::addMovie(Movie* m) {
size++;
Movie **temp = new Movie *[size];
for (int x = 0; x < size; x++) {
temp[x] = array[x];
}
delete [] array;
temp[size-1] = m;
array = temp;
}

void DynArray::cleanup() {
for (int x = 0; x < size; x++)
delete array[x];
delete [] array;
}

int main() {
DynArray *a = new DynArray();
Movie *m = new Movie("sa", 2129, C_COMEDY);
a->addMovie(m);
Movie *k = new Movie("sas", 4324, C_DRAMA);
a->addMovie(k);
Movie *l = new Movie("dsad", 43241, C_DRAMA);
a->addMovie(l);
for (int x = 0; x < a->size; x++) {
a->array[x]->printMovie();
}
a->cleanup();
delete a;
return 0;
}

电影课不是很特别如果需要我可以发布

最佳答案

函数 addMovie 无效。

void DynArray::addMovie(Movie* m) {
size++;
Movie **temp = new Movie *[size];
for (int x = 0; x < size; x++) {
temp[x] = array[x];
}
delete [] array;
temp[size-1] = m;
array = temp;
}

您增加了对象大小并试图访问索引大小为 1 的数组元素,但数组中不存在该元素。循环必须是

  for (int x = 0; x < size - 1; x++) {
temp[x] = array[x];
}

关于c++ - Valgrind 无效读取大小 4 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21700761/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com