vico
vico

Reputation: 18221

Working with string memory

Why delete(pcResult); rices exception in code below?

void strange(char *pcResul)
{
    CString  pss ="123";
    strncpy (pcResul,(LPCTSTR)pss,3);

}

void Dlg::OnBnClickedUser()
{
char *pcResult = new char (10);
strange(pcResult);
delete(pcResult);
}

Upvotes: 2

Views: 64

Answers (2)

R Sahu
R Sahu

Reputation: 206717

You probably meant:

void Dlg::OnBnClickedUser()
{
  char *pcResult = new char[10]; // Allocate an array of `char`, not char with value of 10.
  strange(pcResult);
  delete [] pcResult;
}

Upvotes: 0

Mike Seymour
Mike Seymour

Reputation: 254711

You're only allocating a single character; then you write to it and two bytes of memory after it, giving undefined behaviour.

If you wanted to allocate an array of ten characters, then that's

char *pcResult = new char[10];

and needs to be deleted as an array

delete [] pcResult;

But, unless this is an exercise to learn about low-level memory shenanigans, use std::string to represent strings.

Upvotes: 4

Related Questions