将strcpy()与动态内存一起使用
Using strcpy() with dynamic memory
我的代码运行正常,没有内存泄漏。然而,我得到了valgrind错误:
==6304== 14 errors in context 4 of 4:
==6304== Invalid write of size 1
==6304== at 0x4A0808F: __GI_strcpy (mc_replace_strmem.c:443)
==6304== by 0x401453: main (calc.cpp:200)
==6304== Address 0x4c390f1 is 0 bytes after a block of size 1 alloc'd
==6304== at 0x4A075BC: operator new(unsigned long) (vg_replace_malloc.c:298)
==6304== by 0x401431: main (calc.cpp:199)
==6304== 4 errors in context 2 of 4:
==6304== Invalid read of size 1
==6304== at 0x39ADE3B0C0: ____strtod_l_internal (in /lib64/libc-2.12.so)
==6304== by 0x401471: main (calc.cpp:203)
==6304== Address 0x4c390f1 is 0 bytes after a block of size 1 alloc'd
==6304== at 0x4A075BC: operator new(unsigned long) (vg_replace_malloc.c:298)
==6304== by 0x401431: main (calc.cpp:199)
除了初始地址之外,错误1和3分别与2和4相同
这些错误意味着什么?我该如何修复它们?
int main(){
//Dlist is a double ended list. Each Node has a datum,
//a pointer to the previous Node and a pointer to the next Node
Dlist<double> hold;
Dlist<double>* stack = &hold;
string* s = new string;
bool run = true;
while (run && cin >> *s){
char* c = new char;
strcpy(c, s->c_str()); //valgrind errors here
if (isdigit(c[0]))
stack->insertFront(atof(c));
else{
switch(*c){
//calculator functions
}
delete c;
c = 0;
}
delete s;
s = 0;
valgrind将从stdlib函数中抛出许多通常无害的警告,因为它们有点"作弊"。但这是而不是这里的情况:
char* c = new char; // this is bad
只分配一个字符,而不是一个字符缓冲区,try:
char* c = new char[s->size()+1];
然后将删除更改为:
delete [] c;
char*c=new char;c的大小是1,即使要复制1个字符串,也需要两个字符长的缓冲区(第二个字符用于容纳空终止符)
就在这里:
char* c = new char;
您只分配了一个字符。改为分配阵列:
char* c = new char[str->length() + 1];
还记得调用delete[]。您分配+1为字符串的null终止腾出空间。
char* c = new char;
您正在分配一个字符,然后将一个太长而无法容纳的字符串复制到内存中。您需要分配一个足够大的数组。
相关文章:
- 将字符串存储在c++中的稳定内存中
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- Win32编译器选项和内存分配
- 当vector是tje全局变量时,c++中vector的内存管理
- 将分配的内存与基本数据类型一起使用时,是否需要新放置? std::complex?
- 将 SharedPtr 与 std::list 一起使用时内存泄漏!错误
- 将现有的共享内存与qsharedMemory一起
- 创建两个或多个std::向量时没有bad_alloc,它们一起超过了内存(MSVC)
- 有可能实现一个与数组而不是单个对象一起工作的内存池吗
- 将运算符new和运算符delete与自定义内存池/分配器一起使用
- 与对象一起返回时清除了内存指针
- 将内存清理程序与libstdc++一起使用
- 将strcpy()与动态内存一起使用
- CUDA:将统一内存与类和数组一起使用
- 将 sqlite3 与 C++ 一起使用时出现内存泄漏
- 将 std::vector 与类元素一起使用时出现内存泄漏
- C++11原子学:将它们与内存映射的I / O一起使用是否有意义,或者甚至可能
- 将升压内存池与以向量作为成员变量的类一起使用
- 虚拟内存以及它们是如何结合在一起的
- 将自旋锁与O(1)非内存连续代码一起使用可以吗