c++ - 代码中的段错误

标签 c++ linux segmentation-fault

在这里,我基本上是在尝试输入一个字符串,将其分解成单独的单词并将每个单词分配给一个字符指针 ptr[i]。在执行以下代码时,如果我输入字符串多了一个字,就显示

Segmentation fault (core dumped)

我使用 gdb 进行调试。但在我第二次访问 while 循环后,它显示

程序接收到信号 SIGSEGV,段错误。 来自/lib64/libc.so.6 的 __strlen_sse2 () 中的 0x0000003b64a81321

它的解决方案是在 strcpy(ptr[i],cp); 之前为每个 ptr[i] 分配内存,使用

ptr[i]=new char[sizeof(cp)];.

但是,ptr[0] 不需要内存分配怎么办?如果我不为 ptr[0] 分配内存,是否有可能覆盖其他内容?我出于好奇问它,我知道分配内存总是更好。
这是代码:

#include<iostream>
#include<cstring>
#include<string>
using namespace std;

int main()
{   
    int i,j;
    string s1;
    getline(cin,s1);
    char s[100],*ptr[10];
    strcpy(s,s1.c_str());
    char *cp;

    cout<<"string is:  "<<s1<<endl;
    cp=strtok(s," ");
    i=0;
    while(cp!=NULL)
    { cout<<cp<<endl;
      strcpy(ptr[i],cp);
      cp=strtok(NULL," ");
      i++;
    }

    for(j=0;j<i;j++)
    { cout<<ptr[j]<<endl;
    }
    return 0;
}

最佳答案

当你声明一个局部变量时,它的内容是undefined。所以当你声明一个指针数组时,数组中的指针将指向看似随机的位置。使用未初始化的指针是未定义的行为。未定义的行为可能 导致崩溃,或者它可能 看似有效,但您无法事先预知会发生什么。

您的问题有两种解决方案:

  1. ptr[i] 分配内存(即使 i 为零)。
  2. 将指针 cp 分配给 ptr[i]

在 C++ 中,在空格上拆分字符串比您现有的要简单得多,例如,请参见以下简单程序:

#include <iostream>
#include <vector>
#include <sstream>
#include <algorithm>

int main()
{
    // Put a string into a string stream
    std::istringstream is("hello world how are you today");

    // Vector where to store the "words"
    std::vector<std::string> words;

    // Now split the string on space    
    std::copy(std::istream_iterator<std::string>(is),
              std::istream_iterator<std::string>(),
              std::back_inserter(words));

    // And finally print the words
    for (const auto& word : words)
        std::cout << word << '\n';
}

输出结果是:

hello
world
how
are
you
today

以下是所用函数/类的引用列表:

关于c++ - 代码中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18229395/

相关文章:

C:从函数外部访问指针

rust - 什么是导致段错误的 Rust 代码示例?

c - C 代码的段错误(核心已转储)

C++ 继承 : How to get Size of called object?

C++ 2D 如何将 "stick"宇宙飞船上的排气 Sprite 并允许它相应地旋转?

c++ - 同一个类中的迭代器和 const_iterator 的问题

javascript - [非] contenteditable HTML5 元素上的键盘事件

c - 无法理解以下函数声明

c++ - 对函数的调用是不明确的,但为什么呢?

c - 如何设置 cron 作业以每小时运行一次可执行文件?