为什么我不能执行以下行?

delete [] target;


就我而言

这是代码:

main.cpp

#include <iostream>
using namespace std;
#include "Char.h"

int main()
{
    char * text = "qwerty";
    char * a = new char[charlen(text)+1];
    copyon(a,text);
    cout<<a<<endl;

    char * test = "asdfghjkl";
    assign(&a, test);
    assign(&a, a);

    char * test1 = new char[26];
    for (int i(0); i < 26; i++)
    {
        test1[i] = char(i+65);
    }
    test1[26] = '\0';
    anotherAssign(test1, a);

    cout << test1 << endl;

    return 0;
}


字符集

#include "Char.h"
#include <iostream>
#include <cassert>
#include <cstring>

size_t charlen(const char * ps)
{
    size_t len=0;
    while (ps[len++]);
    assert(len-1==strlen(ps));
    return len;
}
void assign(char** target, const char* source)
{
    if (*target==source)
        return;
    delete [] *target;
    *target = new char[charlen(source)+1];
    copyon(*target, source);
    return;
}

void anotherAssign(char* target, const char* source)
{
    if (target==source)
        return;
    delete [] target;
    target = new char[charlen(source)+1];
    copyon(target, source);
    return;
}

void copyon(char* const target, const char* const source)
{
    char * t = target;
    const char * s = source;
    while (*t++ = *s++);
    //while(*target++ = *source++)
    //  ;
    std::cout << target << " source = " << source << std::endl;
    return;
    size_t len = charlen(source);
    //for (size_t i=0; i<len; ++i)
    //  target[i]=source[i];
    //target[len]='\0';
}


这是一个例外:

c&#43;&#43; - 无法在C&#43;&#43;中删除char指针-LMLPHP
c&#43;&#43; - 无法在C&#43;&#43;中删除char指针-LMLPHP

最佳答案

如果您这样做:

char * test1 = new char[26];


那么您的数组将从test1[0]转到test1[25]

这意味着:

test1[26] = '\0';


超出范围。在这一点上,头部已损坏,接下来发生的事情是不确定的(但很少期望)。

关于c++ - 无法在C++中删除char指针,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47201068/

10-13 09:10