分段故障在main()之前

时间:2014-02-26 04:59:41

标签: c++

我遇到了这段代码的问题。用g ++编译后,运行a.out,我得到一个分段错误,没有显示“here”。代码非常简短:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;

bool inWords(vector<string> words, string str);

int main()
{
  cout << "here";

  vector<string> words;
  string str;
  istringstream iss;
  ifstream file("data.txt", ifstream::in);

  // read in words
  for(int i = 0; file >> str; /*no i++*/)
  {
    if(str[str.length() - 1] == '.')
      str.erase( str.length()-1);
      // if word has a period at the end, erase it

    if(!inWords(words, str))
    {
      // if word is not in vector words, add it
      words.push_back(str);
      i++;
    }
  }

  // output each word
  for (vector<string>::size_type i = 0; i < words.size(); i++)
    cout << words[i];

  // return to beginning of file
  file.clear();
  file.seekg(0, ios::beg);

  // read in sentences
  // to be implemented

  file.close();

  return 0;
}

bool inWords(vector<string> words, string str)
{
  for(int i = 0; !words[i].empty(); i++)
    if(words[i] == str) { return true; }
  return false;
}

据我所知,没有任何问题。 data.txt肯定与文件位于同一目录中,我从命令行中没有收到任何参数。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

它不会在主要之前。尝试使用调试器来查看它发生的位置(例如GDB),这是非常方便的工具。你没有看到“here”的原因是因为缓冲区没有被刷新。在它之后放一个<< std::endl,以便在那时强制输出。

技术性:您可以在main之前进行段错误,但这将在构造函数中发生。我发现你没有在全局范围内定义/实例化自定义对象。

答案 1 :(得分:0)

def aks_agentpool_add(cmd, client, resource_group_name, cluster_name, nodepool_name, kubernetes_version=None, zones=None, enable_node_public_ip=False, node_vm_size=None, node_osdisk_size=0, node_count=3, vnet_subnet_id=None, max_pods=0, os_type="Linux", min_count=None, max_count=None, enable_cluster_autoscaler=False, node_taints=None, tags=None, labels=None, mode="User", no_wait=False): instances = client.list(resource_group_name, cluster_name) for agentpool_profile in instances: if agentpool_profile.name == nodepool_name: raise CLIError("Node pool {} already exists, please try a different name, " "use 'aks nodepool list' to get current list of node pool".format(nodepool_name)) taints_array = [] if node_taints is not None: for taint in node_taints.split(','): try: taint = taint.strip() taints_array.append(taint) except ValueError: raise CLIError('Taint does not match allowed values. Expect value such as "special=true:NoSchedule".') if node_vm_size is None: if os_type.lower() == "windows": node_vm_size = "Standard_D2s_v3" else: node_vm_size = "Standard_DS2_v2" agent_pool = AgentPool( name=nodepool_name, tags=tags, node_labels=labels, count=int(node_count), vm_size=node_vm_size, os_type=os_type, storage_profile=ContainerServiceStorageProfileTypes.managed_disks, vnet_subnet_id=vnet_subnet_id, agent_pool_type="VirtualMachineScaleSets", max_pods=int(max_pods) if max_pods else None, orchestrator_version=kubernetes_version, availability_zones=zones, enable_node_public_ip=enable_node_public_ip, node_taints=taints_array, mode=mode ) _check_cluster_autoscaler_flag(enable_cluster_autoscaler, min_count, max_count, node_count, agent_pool) if node_osdisk_size: agent_pool.os_disk_size_gb = int(node_osdisk_size) return sdk_no_wait(no_wait, client.create_or_update, resource_group_name, cluster_name, nodepool_name, agent_pool) 中对向量进行迭代的技术是错误的,并且会与超过向量末端的元素进行交互,从而导致分割错误。

inWords向量为空且words[0](向量的第一个元素)尚不存在时,此程序立即访问inWords中的words,因为向量仍然为零,但循环不会做任何事情来避免这种情况。

我认为words[0]可以用inWords更好地实现,也许是这样的:

std::find

请记住bool inWords(const vector<string>& words, const string& str) { return std::find(words.begin(), words.end(), str) != words.end(); } 以使用#include <algorithm>。我还更改了参数以通过const引用传递,因此您需要更改该函数的前向声明。我还向输出中添加了std::find以使其可读。

全文修复:

endl