I am new to C and I was playing around with the program and wrote this program
int main(){
char ** charList ;
int listSize = 5;
for(int a = 0; a < listSize; a ){
char str [2];
gets(str);
charList[a] = str;
}
printf("program ended");
return 0;
}
Which takes 5 inputs from terminal and prints program ended.
On the other hand, If I add simple empty for loop after printf("program ended");
as the code below.
int main(){
char ** charList ;
int listSize = 5;
for(int a = 0; a < listSize; a ){
char str [2];
gets(str);
charList[a] = str;
}
printf("program ended");
for(int b = 0; b < 0; b ){
printf("loop");
}
return 0;
}
I only added empty for loop and the program crashed. It only waits for one input and crashes. As much as I understood it might be a buffer error. But I could not understand how an empty loop crashes working program. Can someone explain what is wrong with the program.
CodePudding user response:
- You do not allocate any memory to store the pointers.
char ** charList;
/*...*/ //
charList[a] = str; <-- access outside the bounds.
Solution:
int listSize = 5;
char *charList[listSize];
or
char **charList = malloc(listSize * sizeof(*charList));
Do not use
gets
. usefgets
instead (but your char array should be larger than two chars as you will read\n
as well.charList[a] = str;
will assign the reference to the same memory so all elements ofcharList
array will reference the same string. You need to allocate memory for the string and copy it.
char charList[listSize][3];
/* ... */
strcpy(charList[a],str);
or
charList[a] = malloc(strlen(str) 1);
if(charList[a]) strcpy(charList[a],str);