runtime error (stack overflow)

2020-01-29 03:09发布

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?

2条回答
我想做一个坏孩纸
2楼-- · 2020-01-29 03:26

char *options[100000] allocates 100000 string pointers, not strings. scanf is being passed gibberish.

查看更多
【Aperson】
3楼-- · 2020-01-29 03:29

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).

-----------------
|  Your stack   |
| (grows down)  |
|               |
-----------------
|               |
|               |
|               |
|               |
|               |
|               | -- max stack size is here
|               |
|               |
|               |
|               |
|               |
-----------------
|   Your heap   |
|   (grows up)  |
|               |
-----------------

And then you try to allocate a bunch of really big arrays and run out of space

-----------------
|  Your stack   |
| (grows down)  |
|               |
|               |
|               |
|               |
|               |
|               |
|               |
|               | -- max stack size is here
|               |
----------------- -- what you actually need
|               |
|               |
|               |
|               |
-----------------
|   Your heap   |
|   (grows up)  |
|               |
-----------------

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 using free, 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.

查看更多
登录 后发表回答