segmentation fault while parsing a list of integers
int num_arrays;
char *p[20];
char tempc;
int i=0;
do
{ p[i]=malloc(sizeof(int));
scanf("%s",p[i]);
tempc=*p[i];
++i;
}while(tempc=='x');
num_arrays=atoi(p[0]);
When i write num_arrays=atoi(..)
,gcc give me segmentation fault or memory
stack is exceeded, I don't understand why it behaves like that
can anyone explai开发者_运维百科n, why?
You haven't allocated any memory in p
, so its elements point to random locations. You can allocate memory for strings with a maximum length of 100 like this:
int i;
for (i = 0; i < 20; i++)
p[i] = malloc(101);
Or else you want an array of characters, not of strings, in which case you should declare it like
char p[20];
In this case, you must not try to read strings into each element with scanf though.
Update after the missing code part has been added:
You are allocating sizeof(int)
bytes of memory for your strings, which is most likely 4, i.e. your input strings read by scanf
must not be longer than 3 characters. Otherwise you have a buffer overrun error, which may lead to the segmentation fault you are struggling with.
Moreover, tempc=p[i]
assigns a pointer value to a character variable! This value, converted to a character, will almost surely never be equal to 'x'
.
I guess you are trying to get the first character of p[i]
, which would be p[i][0]
or *p[i]
.
I also suspect that your loop condition is the opposite of what you had in mind: right now the loop repeats as long as tempc
is equal to 'x'
- you probably wanted to repeat until tempc
becomes 'x'
. And you should also check for your loop not running more than 20 times:
...
}while(tempc != 'x' && i < 20);
You are not allocating memory for your strings. (Edit: Now you are)
You may also want to make sure you are not doing more than 20 iterations since your array of char* only has 20 elements.
Also assuming sizeof(int) == 4, your strings must not be greater than 4 chars as you have now and 1 of those needs to be a null termination. You may want to allocate more room for those input strings.
精彩评论