分段 Linux Ubuntu 中的 g++ 错误,但在 Windows 中的 g++/MingW 中,在 C++ 中打
Segmentation Fault with g++ in Linux Ubuntu, but not with g++/MingW in Windows, when printing a char string in C++
我有一个程序,它:
- 创建一个包含 3 个
char
指针的数组,char *z_str[3];
. - 分配类型为
char
的动态内存对象,并将返回的指针分配给这些char
指针。 - 提示用户提供输入字符串。
- 打印提供的字符串。
源代码:
#include <iostream>
using namespace std;
int main()
{
char *z_str[3];
int i;
for(i = 0; i < 2; i++)
{
z_str[i] = new char [30];
if(z_str[i] == NULL)
{
cout << "Memory for String " << i+1 << " could not be allocated!" << endl;
cout << "Program terminates.";
return 1;
}
}
cout << endl << endl;
cout << "Please input the first string [max.29 characters]:" << endl;
cin >> z_str[0];
cout << endl;
cout << "Please input the second string [max.29 characters]:" << endl;
cin >> z_str[1];
cout << endl;
cout << "Please input the third string [max.29 characters]:" << endl;
cin >> z_str[2];
cout << endl << endl;
cout << "First string is:" << endl;
cout << z_str[0] << endl << endl;
cout << "Second string is" << endl;
cout << z_str[1] << endl << endl;
cout << "Third string is:" << endl;
cout << z_str[2] << endl << endl;
return 0;
}
当我在 Linux Ubuntu 中使用 g++ 编译此代码并运行代码时,当程序将char
字符串打印到 CLI 中时,我遇到了分段错误。
端子输出:
Please input the first string:
string1
Please input the second string:
string2
Please input the third string:
string3
Segmentation fault (core dumped)
现在,如果我在Windows 10中使用g ++/MingW编译相同的代码,那么一切都可以在PowerShell中正常工作:
Please input the first string:
string1
Please input the second string:
string2
Please input the third string:
string3
First string is:
string1
Second string is
string2
Third string is:
string3
- 为什么我在 Linux Ubuntu 中打印字符字符串时遇到 g++ 的分段错误,而在 Windows 中的 g++/MingW 中却没有出现C++?
循环
for(i = 0; i < 2; i++)
会让你初始化z_str[0]
和z_str[1]
,但不会z_str[2]
。
因此,当您在z_str[2]
中使用未初始化和不确定的值时,您会得到未定义的行为(和崩溃(。
您需要增加循环以迭代所有元素:
for(i = 0; i < 3; i++)
所有这些都有更好的解决方案,我建议使用std::string
对象的std::array
:
std::array<std::string, 3> z_str;
现在你不需要自己做任何动态分配,数组中的所有三个字符串都将是默认构造的,这意味着它们将是空(但有效(的字符串。
如果您不允许使用std::array
或std::string
,还有其他方法可以改进您的程序,例如使用范围for
循环:
for (auto& str_ptr : z_str)
str_ptr = new char[30];
上面的循环保证遍历数组的所有元素。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- .cpp和.h文件中的模板专用化声明
- 反向给定链表中的K节点
- 正在查找文档以获得PS4平台的C++中的设备信息
- enum是C++中的宏变量还是整数变量
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 将字符串存储在c++中的稳定内存中
- 文本文件中的单词链表
- 递归函数计算序列中的平方和(并输出过程)
- 如何从C++中的依赖类型中获得它所依赖的类型
- C++中的"inline"关键字
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 用C++中的一个变量定义一个常量
- vector.resize()中的分配错误
- 使用指针从C++中的数组中获取最大值
- arr[-1]在c++中的奇怪行为
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 将值指定给向量(2D)的向量中的某个位置
- 内置函数可查看CPP中的成员变量