I've got this code in C language:
char *options[100000];
int k[100000];
char *param[100000];
int n;
int i,j;
...
scanf("%d",&n);
for (i=0;i<n;i++)
{
scanf("%s%d",&options[i],&k[i]);
param[i]="On";
}
...
just as the programm reaches this point:
scanf("%s%d",&options[i],&k[i]);
I get the runtime error (stack overflow). The input here should be like this:
word1 number1
word2 number2
and so on. I've got no idea why is this happening. What's the problem?
char *options[100000] allocates 100000 string pointers, not strings. scanf is being passed gibberish.
Ok... so I thought someone would provide an answer to your stack overflow problem but so far everybody only mentioned a problem you actually have (more on this later) that is unrelated to the stack overflow (it'll be problematic but only once you fix this first).
And then you try to allocate a bunch of really big arrays and run out of space
So you get a run-time error (stack overflow) because you've tried to use more stack space than what you have available.
The trick here is to use heap allocation (because on most platforms, at least all the ones I've heard of) the heap is massively bigger than the stack.
To allocate memory on the heap you use
malloc
(also, when you're done with it don't forget to release the memory usingfree
, or else you'll leak the memory).EDIT: Bonus: The other problem you have. Other answers seem to indicate you're access/dereferencing/using memory that's not allocated. You're partially actually fine on this point.
You scanf call point to a char array (here's the problem) and an int in the array k (no problem. So right now all the entries in the options array point to nowhere/anywhere. You need to allocate memory for them (again using
malloc
).As for strdup it allocates the memory itself and returns the pointer, again no problem here. Just don't forget to free it after you're done using it because again this would be a memory leak.