我正在尝试在C ++中使用C标准库,只是为了看看我是否记得很清楚......结果我没有...... 但是,我在堆上分配了一些字符串,当我尝试删除它们时,我得到访问冲突和崩溃..
#include <climits>
#include <cstring>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
void substr(char* str, std::size_t offset, std::size_t pos, char* buffer)
{
for (unsigned i = offset, j = 0; i < pos; ++i, ++j)
buffer[j] = str[i];
}
void substr(char* str, std::size_t pos, char* buffer)
{
substr(str, pos, strlen(str), buffer);
}
int countstr(char* StringToSplit, char* Delimiter)
{
int count = 0;
char* ptr = strstr(StringToSplit, Delimiter);
while(ptr != NULL)
{
++count;
ptr = strstr(ptr + 1, Delimiter);
}
return count;
}
void SplitString(char* StringToSplit, char* Delimiter, char** Result)
{
int i = 0;
char* ptr = strtok(StringToSplit, Delimiter);
while(ptr != NULL)
{
Result[i] = (char*)malloc(strlen(ptr) + 1);
strcpy(Result[i], ptr);
ptr = strtok(NULL, Delimiter);
++i;
}
}
int main()
{
char str[] = "Hello there nooby noob";
int len = countstr(str, " ");
char** strs = (char**)malloc(len * sizeof(char*));
SplitString(str, " ", strs);
for (int i = 0; i < len + 1; ++i)
{
printf("%s, ", strs[i]);
}
for (int i = 0; i < len + 1; ++i)
{
free(strs[i]);
}
free(strs);
}
打印:
"Hello, there, nooby, noob".
这是正确的。我唯一的问题是释放我的分配。它出于某种原因不会让我。
我做错了什么?
答案 0 :(得分:3)
循环
while(strs != NULL)
delete[] strs[j++];
不起作用。 delete
不会影响strs的值(实际上你不想这样),所以你一遍又一遍地删除相同的字符串。