首页 \ 问答 \ 尝试将stdin读取到2d动态分配的数组时出现分段错误(Segmentation fault when trying to read stdin to a 2d dynamically allocated array)

尝试将stdin读取到2d动态分配的数组时出现分段错误(Segmentation fault when trying to read stdin to a 2d dynamically allocated array)

我正在尝试从stdin读取动态的字符串数组,使用空格作为分隔符。 代码如下

#include<stdio.h>
#include<stdlib.h>
char** parseInput(size_t *numElements)
{
  char **lines;
  int outerIndex = 0;
  int innerIndex = 0;
  int widths = 1;
  char c=getchar();
  lines =(char**) malloc((outerIndex+1)*sizeof(char*));
  lines[0] = (char*) malloc(sizeof(char));
  while(c!=EOF)
  {
    if(innerIndex==widths)//reallocate each strings length, double it
    {
      widths+=widths;
      int i;
      for(i=0;i<outerIndex+1;i++)
        lines[i]=(char*)realloc(lines[i],(widths+1)*sizeof(char));
    }
    lines[outerIndex][innerIndex]=c;
    innerIndex++;
    if(c==' ')//allocate memory for the next string in the array of strings
    {
      lines[outerIndex][innerIndex]='\0';
      innerIndex=0;
      outerIndex++;
      lines =(char**) realloc(lines,(outerIndex+1)*sizeof(char*));
      lines[outerIndex] = (char*) realloc(lines[outerIndex],(widths+1)*sizeof(char));
      //the above line in the debugger causes a segfault when outerIndex=19
    }
    c=getchar();
  }
  if(innerIndex!=0)//if the last character is not a space, append a space
  {
    if(innerIndex==widths)
    {
      widths+=widths;
      int i;
      for(i=0;i<outerIndex+1;i++)
        lines[i]=(char*)realloc(lines[i],(widths+1)*sizeof(char));
    }
    lines[outerIndex][innerIndex]=' ';
    lines[outerIndex][innerIndex+1]='\0';
  }
  *numElements=(size_t)(outerIndex+1);
  return lines;
}
int main()
{
    size_t num =0;
    char** lines = parseInput(&num);
}

当外部数组大小增加到超过20个变量时,我在指示的行处出现分段错误。 例如,以下输入会导致段错误

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

但以下没有

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

调试错误说

Program received signal SIGSEGV, Segmentation fault.
0x0000003417e7bf4d in realloc () from /lib64/libc.so.6

这可能是由什么引起的?


I'm trying to read from stdin to a dynamic array of strings, using spaces as separators. The code is as follows

#include<stdio.h>
#include<stdlib.h>
char** parseInput(size_t *numElements)
{
  char **lines;
  int outerIndex = 0;
  int innerIndex = 0;
  int widths = 1;
  char c=getchar();
  lines =(char**) malloc((outerIndex+1)*sizeof(char*));
  lines[0] = (char*) malloc(sizeof(char));
  while(c!=EOF)
  {
    if(innerIndex==widths)//reallocate each strings length, double it
    {
      widths+=widths;
      int i;
      for(i=0;i<outerIndex+1;i++)
        lines[i]=(char*)realloc(lines[i],(widths+1)*sizeof(char));
    }
    lines[outerIndex][innerIndex]=c;
    innerIndex++;
    if(c==' ')//allocate memory for the next string in the array of strings
    {
      lines[outerIndex][innerIndex]='\0';
      innerIndex=0;
      outerIndex++;
      lines =(char**) realloc(lines,(outerIndex+1)*sizeof(char*));
      lines[outerIndex] = (char*) realloc(lines[outerIndex],(widths+1)*sizeof(char));
      //the above line in the debugger causes a segfault when outerIndex=19
    }
    c=getchar();
  }
  if(innerIndex!=0)//if the last character is not a space, append a space
  {
    if(innerIndex==widths)
    {
      widths+=widths;
      int i;
      for(i=0;i<outerIndex+1;i++)
        lines[i]=(char*)realloc(lines[i],(widths+1)*sizeof(char));
    }
    lines[outerIndex][innerIndex]=' ';
    lines[outerIndex][innerIndex+1]='\0';
  }
  *numElements=(size_t)(outerIndex+1);
  return lines;
}
int main()
{
    size_t num =0;
    char** lines = parseInput(&num);
}

When the outer array size grows to anything more than 20 variables, I get a segmentation fault at the indicated line. For example the following input causes a segfault

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

but the following does not

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

The debug error says

Program received signal SIGSEGV, Segmentation fault.
0x0000003417e7bf4d in realloc () from /lib64/libc.so.6

What could this be caused by?


原文:https://stackoverflow.com/questions/41990269
更新时间:2023-10-21 10:10

最满意答案

由于您有数组数组,并且您需要每个子数组中的关键字0下的值,所以您的代码可以是:

foreach ($file as $pos) {
    echo $pos[0];
}

As you have array of arrays and you need values under key 0 in each subarray, your code can be:

foreach ($file as $pos) {
    echo $pos[0];
}

相关问答

更多
  • 而不是写出值考虑使用fputcsv() 。 这可能会立即解决您的问题。 Instead of writing out values consider using fputcsv(). This may solve your problem immediately.
  • 我会用StringIO : try: # for Python 2.x from StringIO import StringIO except ImportError: # for Python 3.x from io import StringIO import csv scsv = """text,with,Polish,non-Latin,lettes 1,2,3,4,5,6 a,b,c,d,e,f gęś,zółty,wąż,idzie,wąską,dróżką, ...
  • 老兄,你去吧。 $export_data = array_replace(array_map(function($v){return null;}, range(0, max(array_keys($export_data)))), $export_data); 测试100,000次迭代,结果以秒为单位: Version Run1 Run2 Run3 PHP 5.6.20 .58 .55 .50 PHP 7.0.5 .18 .21 .21 现在为了解释,所以我不会被贬低 ...
  • 正如@ splah58所说,你必须在追加模式下打开文件来添加数据,如下所示: if( !isset( $_SESSION["origURL"] )) $_SESSION["origURL"] = @$_SERVER["HTTP_REFERER"]; $referer = @$_SERVER['HTTP_REFERER']; $userAgent = @$_SERVER['HTTP_USER_AGENT']; $date = date('Y-m-d H:i:s'); $visitorData = ar ...
  • HTML确实会被输出,因为这是你的代码所做的第一件事。 正如您已经知道的那样,通过使用标记来表示PHP代码的开始和结束,PHP允许在单个文件中混合使用HTML和代码。 这些标记之外的所有内容都被认为是输出,并以与使用print()或echo()语句完全相同的方式发送给浏览器。 你的代码从一块HTML开始,没有任何东西。 这与您使用包含此HTML的print()语句启动程序完全相同。 如果您不希望在任何情况下输出HTML,那么在它之前需要一些代码来告诉它何时以及是否输出它。 The HTML ...
  • 如果要将标签{name}替换为$a = array('name' => 'value'); 你可以使用str_replace(); $filehtml = file_get_contents('file.html'); $array = array('var' => 'value'); foreach($array as $tag => $value) { $filehtml = str_replace('{'.$tag.'}', $value, $filehtml); } echo $fileht ...
  • 需要更新for循环内for代码。 更新为: for ($c = 0; $c < $num; $c++) { if (isset($arr[$data[0]]) && isset($arr[$data[0]][$data[1]])) { $arr[$data[0]][$data[1]] .= "," . $data[$num - 1]; } else { $arr[$data[0]][$data[1]] = $data[$num - 1]; } ...
  • 这应该工作: $entities = array(); $header = fgetcsv($handle, 0, ";"); // save the header while (($values = fgetcsv($handle, 0, ";")) !== FALSE) { // array_combine // Creates an array by using one array for keys and another for its values $entities[] ...
  • 由于您有数组数组,并且您需要每个子数组中的关键字0下的值,所以您的代码可以是: foreach ($file as $pos) { echo $pos[0]; } As you have array of arrays and you need values under key 0 in each subarray, your code can be: foreach ($file as $pos) { echo $pos[0]; }
  • 我不喜欢你的代码。 如果有数千个数据并循环每个数据然后插入数据库,该怎么办? 有一个mysql查询将csv文件导入数据库表。 source: how-to-import-csv-file-to-mysql-table Ok, I have found an answer to my question. I built a small app for personal use where I can keep the content for auctions I list online. Some of th ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)