首页 > 解决方案 > 在 C++ 中调整数组大小时如何修复错误?

问题描述

我有一个小程序,它返回一行输入的字符:

#include <iostream>

char *resize(const char *str, unsigned size, unsigned new_size);  

char *resize(const char *str, unsigned size, unsigned new_size)
{
    char * m = new char[new_size];
    for (int i = 0; i < size && i < new_size; ++i) {
        m[i] = str[i];
    }
    delete [] str;
    return m;
}


char *getline()
{
    char ch;
    std::cin >> ch;

    int size = 1;
    char * str = new char[size];
    char * m;

    while (std::cin.get(ch) && ch != '\n') {

        str[size-1] = ch;
        m = resize(str, size, ++size);
        m[size] = '\0';

    }
    return m;
}

但这给了我一个错误:

失败的测试#1。在抛出“std::logic_error”what() 实例后调用运行时错误终止:发生内存泄漏或双重分配已中止(核心转储)

我不完全明白问题出在哪里,因为我是 C++ 新手。如何解决问题?

标签: c++memory-managementundefined-behaviorc-strings

解决方案


这里有一个问题:m = resize(str, size, ++size);. 未指定函数参数的求值顺序,因此允许编译器size在将 的值size作为第二个参数传递之前递增。将代码重写为m = resize(str, size, size+1); ++size;.


推荐阅读