为什么我会为以下代码获得seg错误? [英] Why do I get a seg fault for the following code?

查看:84
本文介绍了为什么我会为以下代码获得seg错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试动态地将内存分配给argc的输入,但是继续得到一个段错误



我尝试过:



I'm trying to dynamically allocate memory to the input of argc, but keep getting a seg fault

What I have tried:

int main(int argc, char* argv[])
{
  int n = argc;

  char** argv_inputs = malloc(n * sizeof(char*));
  int* array_of_ints = malloc(n * sizeof(int));



  int i, sum, index;

  if (argc < 3)
  {
    printf("Error: too few arguments");
  }
  else
  {
    for(i = 2; i <= n; i++)
    {
      argv_inputs[i-2] = argv[i];
    }

    string_to_int(argv_inputs, array_of_ints, n-1);
    }
  return(0);
}

推荐答案

argc是argv中的位置数

所以argv有来自的位置0到argc-1



然后你设置n = argc

所以argv的位置从0到n-1



但你的for循环说(i = 2; i< = n; i ++)

所以最终它设置为i = n

在这种情况下当你访问argv [i]

你实际上是在访问argv [n]

这是在内存中的数组之外你没有拥有。
argc is the number of locations in argv
So argv has locations from 0 to argc-1

And then you set n=argc
So argv has locations from 0 to n-1

But your for loop says for(i = 2; i <= n; i++)
So eventually it sets i=n
In that case when you access argv[i]
You are actually accessing argv[n]
And that is outside the array in memory you don't own.


你可以简化你的代码,你不需要 argv_inputs

You can simplify your code, you don' t need argv_inputs
string_to_int(argv[2], array_of_ints, n-1);



在没有复制的情况下也能正常运行,因为 n-1 的参数太多,它也会崩溃。



您应该学习调试器,它会帮助您找到自己的错误。



有一个工具可以让你看到你的代码在做什么,它的名字是调试器。它也是一个很好的学习工具,因为它向你展示了现实,你可以看到哪种期望与现实相符。

当你不明白你的代码在做什么或为什么它做它做的时候,答案就是答案是调试器

使用调试器查看代码正在执行的操作。只需设置断点并查看代码执行情况,调试器允许您逐行执行第1行并在执行时检查变量。



调试器 - 维基百科,免费的百科全书 [ ^ ]



掌握Visual Studio 2010中的调试 - 初学者指南 [ ^ ]

使用Visual Studio 2010进行基本调试 - YouTube [ ^ ]

调试器在这里向您展示您的代码正在做什么,您的任务是与什么进行比较应该这样做。

调试器中没有魔法,它没有找到错误,它只是帮助你。当代码没有达到预期的效果时,你就会接近一个错误。


will work the same without copying, it will crash the same too because n-1 is 1 argument too much.

You should learn the debugger, it will help you to find what is wrong by yourself.

There is a tool that allow you to see what your code is doing, its name is debugger. It is also a great learning tool because it show you reality and you can see which expectation match reality.
When you don't understand what your code is doing or why it does what it does, the answer is debugger.
Use the debugger to see what your code is doing. Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.


这篇关于为什么我会为以下代码获得seg错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆