G
G
German2019-04-13 19:24:12
C++ / C#
German, 2019-04-13 19:24:12

Crash when deleting dynamic array?

When I delete - an exception.
Why? explain in as much detail as possible.
The code:

Data parseAnswerFromCOM(const char* source)
{
  Data data = { };
  char *s = new char[strlen(source) + 1];
  char *next_token1 = NULL;
  strcpy_s(s, strlen(s), source);
  char *p = strtok_s(s, ";", &next_token1);
  int tmpCounter = 0;
  while (p != NULL)
  {
    cout << p << endl;
    p = strtok_s(NULL, ";", &next_token1);
  }
  delete[] s;
  return data;
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jcmvbkbc, 2019-04-13
@jcmvbkbc

char *s = new char[strlen(source) + 1];
...
strcpy_s(s, strlen(s), source);

strlen(s)-- generally beyond good and evil and returns a random number, by and large. Because s is a newly allocated uninitialized array.
The call strcpy_sis completely meaningless and wrong. Pointless, because you just allocated as much memory as there is data in the row. strcpy_s makes sense if the buffer you're copying to is a fixed-length array. Incorrect, because even if you meant strlen(source), and not strlen(s), you had to pass strlen(source) + 1, so that there is where to copy the 0-terminator. Among other things, strcpy_s also returns an error code, which makes sense to check.
The best thing to do in this place would be to call memcpy(s, source, strlen(source) + 1);or even throw it out s = new char [...]; strcpy_s ... delete [] s;and replace it with s = strdup(source); ... free(s);
If you really want strcpy_s, then at least like this:strcpy_s(s, strlen(source) + 1, source);
Fixing this place will fix delete as well, because delete fails because you broke the heap.

E
Evgeny Petryaev, 2019-04-14
@Gremlin92

Remove [] from delete

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question