【发布时间】:2018-11-01 17:22:06
【问题描述】:
为了从给定路径获取父目录,我有以下代码。 注意:size_t 是 unsigned int 的 typedef。
/****************************************************
This function takes a full path to a file, and returns
the directory path by returning the string up to the last backslash.
Author: Aashish Bharadwaj
*****************************************************/
_TCHAR* GetDirectoryFromPath(const _TCHAR* path)
{
size_t size = _tcslen(path);
size_t lastBackslash = 0;
for (size_t i = 0; i < size; i++)
{
if (path[i] == '\\')
{
lastBackslash = i;
}
}
_TCHAR* dirPath = new _TCHAR();
size_t i;
for (i = 0; i <= lastBackslash; i++)
{
dirPath[i] = path[i];
}
dirPath[i + 1] = '\0'; //THIS IS VERY NECESSARY! Otherwise, a bunch of garbage is appended to the character array sometimes.
return dirPath;
}
我想知道是否有人知道这是什么以及为什么这样做。
【问题讨论】:
-
_TCHAR* dirPath = new _TCHAR();分配了多少个_TCHAR? -
" 它分配一个指向未指定大小的 _TCHAR 数组的指针。它会在您向其附加字符时自动调整大小。" - 这两种说法都是错误的。
-
听起来你真的可以使用good C++ book。您对手动内存管理的工作方式有很多误解,并且程序无法按预期工作的事实证明您的数组分配不正确。
-
“它会自动调整大小”——不,它不会。 “这就是堆的工作方式” - 不,不是。如果您只是想否认所提供的知情建议的有效性,那么在这里提问真的没有意义。
-
@AashishBharadwaj 该代码具有未定义的行为并且正在破坏内存,因为它正在访问它尚未分配的非法内存。
new int()分配 1 且仅 1int。howdy[0]和*(howdy+0)在这种情况下有效,但howdy[1]和*(howdy+1)超出范围且无效。