Click here to Skip to main content
15,912,977 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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);
}
Posted
Updated 11-Sep-17 17:23pm
Comments
Mohibur Rashid 11-Sep-17 21:29pm    
Your for loop is running extra mile
Jochen Arndt 12-Sep-17 2:55am    
Did you read my answer to your previous question?

There I noted already that the loop is iterating over the wrong range.

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.
 
Share this answer
 
v4
You can simplify your code, you don' t need argv_inputs
C++
string_to_int(argv[2], array_of_ints, n-1);

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.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900