trafalgarLaww
trafalgarLaww

Reputation: 515

Can not delete char pointer in C++

Why can not I perform the following line?

delete [] target;

in my case?

Here is the code:

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;
}

Char.cpp

#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';
}

Here is an exception:

enter image description here enter image description here

Upvotes: 0

Views: 709

Answers (1)

Steve
Steve

Reputation: 1757

If you do:

char * test1 = new char[26];

then your array will go from test1[0] to test1[25].

That means:

test1[26] = '\0';

is out of bounds. At this point, the head is corrupted, and what happens next is undefined (but rarely desirable).

Upvotes: 3

Related Questions