Reputation: 51
I'm new to C and I'm trying to convert all strings that the user typed in the command line to integers and store them into a new array, so that I can use it later. But I get a "segmentation fault (core dumped)" issue.
Can someone check with my code and point out the error(s)?
int main(int argc, char *argv[]) {
long int conv[argc - 1];
for (int i = 0; i < argc; i++) {
conv[i] = strtol(argv[i + 1], NULL, 10);
}
If I run this program like, ./main 1 2 3
, then {1, 2, 3}
should be stored in the new array of integers.
Upvotes: 1
Views: 73
Reputation: 51874
Your loop attempts to access an "out-of-bounds" array element on its last iteration: if you run the program with, say, ./main 1 2 3
, then argc
will be 4 and the last argument will be in argv[3]
. However, when the loop index, i
is 3, the loop will still run and you will be attempting to read argv[i + i]
– which is argv[4]
and thus beyond the end of the array.
You can simplify your loop (or, at least, rewrite it) to use the actual i
value for the argv
index and i - 1
for the conv
index; but, of course, you then need to start the loop with i = 1
:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
long int conv[argc - 1];
for (int i = 1; i < argc; i++) {
conv[i - 1] = strtol(argv[i], NULL, 10);
}
// Data check:
for (int j = 0; j < argc - 1; ++j) {
printf("Data %d is %ld\n", j, conv[j]);
}
return 0;
}
Upvotes: 1
Reputation: 791
The arguments you pass in to your program are stored in argv[1]
to argv[argc-1]
, so you'd want to change the for loop to something like this: for (int i = 1; ...) {...}
. Also, with strtol(argv[i+1],NULL,10);
, when i==argc-1
, you're trying to access the array out of bounds.
Here's a modified version of your code with the fixes applied:
int main(int argc, char *argv[]){
long int conv[argc-1];
for(int i=1;i<argc;i++){
conv[i-1]=strtol(argv[i],NULL,10);
}
}
Upvotes: 1