字符串分割错误
segmentation fault in string
我只是想从字符串中提取两个子字符串。但它显示出分割错误。
代码为
const char *str;
char *s1, *s2;
str = "name:d";
char *pos = strchr(str, ':');
size_t no = 1,
index = pos - str;
if (index > 0)
{
strncpy(s1, str, index);
cout << "name is:" << s1;
index++;
strncpy(s2, str + index, no);
cout << "direction is:" << s2;
}
将以下两行复制到未初始化指针引用的内存中:
strncpy(s1,str,index);
strncpy(s2,str+index,no);
您需要为s1
和s2
分配内存(或者只使用std::string
,避免自己的头痛)。
您没有为s1
或s2
分配任何内存。您需要做的是使用new
并分配内存,或者使用std::string
并节省麻烦。
您没有初始化s1
或s2
来指向任何东西;因此,试图写入他们指向的内存(例如strncpy(s1,str,index)
)会给出未定义的行为-如果你幸运的话,一个分段错误。
如果你在写C,那么为它们分配内存;如果您正在编写c++,请使用std::string
为您管理内存分配。
相关文章:
- C++映射分割错误(核心转储)
- 由cin中的字符串中未捕获空白引起的分割错误
- 删除映射和分割错误中的一个过去结束元素
- 在指向函数中读取变量时出现分割错误
- 在链表中的第 n 位插入显示分割错误
- 较高值 n 的分割错误(例如 n=999997)
- 尝试通过memcpy复制大尺寸浮点向量时的分割错误
- 分割错误:向量中的擦除功能
- 向量向量的分割错误
- 我在C++中编写了一个方法来打印树类的预序,但它显示了分割错误
- C ++分割错误,为什么使用"long long"我没有得到答案?
- 在尝试使用递归查找集合子集的总数时,我遇到了分割错误
- 分割错误 11:尝试使用 cin 输入 B[1] 时
- 集合布局上的 Qt 分割错误
- 高达20亿的筛子会产生分割错误
- G :内部编译器错误:分割故障(程序CC1PLUS) - 我在哪里开始
- 二进制搜索树操作程序错误:分割故障(核心倾倒)
- 在给出正确的输出后,给出错误分割错误(核心转储)
- 得到错误分割错误(核心转储)进程返回139 (0x8B)
- 内部编译错误:分割错误在gcc.发送可变模板到struct时