search

Home  >  Q&A  >  body text

C++内存管理问题,如何删除char *

以下代码为什么会报错,以及如何正确删除ch,释放内存。

char *ch = new char(100);
char tmp[10] = "e100";
strtod(tmp, &ch);
cout << *ch << endl;
delete ch;
system("pause");
天蓬老师天蓬老师2886 days ago600

reply all(2)I'll reply

  • 迷茫

    迷茫2017-04-17 11:08:25

    You wrote it wrong, it should be new char[100], and the delete statement should be delete[] ch. New char(100) means to construct a char and initialize the value to 100.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 11:08:25

    The usage of strtod function is wrong here - it’s okay to say that ch is not initialized

    Please check strtod usage:
    http://baike.baidu.com/view/1876981.h...

    ch has not been initialized, and its content is uncertain. It is very likely that strtod will not encounter the end of string symbol ("NULL")

    Also, the last sentence delete[] ch is better.

    reply
    0
  • Cancelreply