我目前正在开发一个包含一些文件 I/O 的项目。
由于它是跨平台的,我需要考虑不同的路径分隔符,因此决定创建以下函数来简化加入路径的过程:
/**
* @brief Joins two paths together.
*
* path = a + seperator + b + '\0'
*
* @param a First path.
* @param b Second path.
*
* @return A pointer to the two paths combined.
*/
char * join_paths(const char * a, const char * b)
{
const char separator[] =
#ifdef _WIN32
"\\";
#else
"/";
#endif
/* Get the sizes of all the strings
to join. */
size_t a_len = strlen(a);
size_t b_len = strlen(b);
size_t s_len = strlen(separator);
size_t total_len = a_len + b_len + s_len + 1; /* +1 for \0 */
/* path will contain a, b, the separator and \0
hence the total length is total_len.
*/
char * path = malloc(total_len);
check( path != NULL,
"Error allocating memory for path. " );
memcpy(path, a, a_len); /* path will begin with a */
strncat(path, separator, s_len); /* copy separator */
strncat(path, b, b_len); /* copy b */
error:
return path;
}
(这里check
的宏在哪里:http: //pastebin.com/2mZxSX3S)
直到现在一直运行良好,当我不得不使用 GDB 调试与文件 I/O 无关的东西时,我意识到我所有的文件路径似乎都已损坏(例如“¡║¯½½½½½½■¯■¯■¯■” )。
我也收到错误消息:
“释放后修改的空闲堆块”
经过进一步调查,我意识到这一切都发生memcpy
在join_paths
.
然而,这一切似乎只发生在从 GDB 运行它时。这里出了什么问题?