I'm doing a certain project for college, which consists in reading an input text, and generating a certain output, based in several commands. The focal point for grading is the efficiency, so dynamic memory allocation is the way to go, yet I'm really shaky in my knowledge of it.
Either way, the program compiled just fine, but when I ran it, it fast showed a segmentation fault, and I'm almost sure the reason is my poor handling of the memory. After I tried to diagnose it with gdc, I got this:
(gdb) run proj
Starting program: /home/dusk/Documents/proj proj
warning: no loadable sections found in added symbol-file system-supplied DSO at 0x7ffff7ffa000
5
hello, I'm me
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7a681c3 in _IO_vfscanf () from /lib/x86_64-linux-gnu/libc.so.6
(gdb) where
#0 0x00007ffff7a681c3 in _IO_vfscanf () from /lib/x86_64-linux-gnu/libc.so.6
#1 0x00007ffff7a70a22 in __isoc99_scanf ()
from /lib/x86_64-linux-gnu/libc.so.6
#2 0x00000000004009a4 in linelist (n=5) at proj.c:79
#3 0x000000000040134b in main () at proj.c:226
So apparently, the problem (well... the first problem) is in the linelist function, which is as follows:
/* Creates a list of strings (each being a line of the input)
implemented with pointers */
char **linelist(int n)
{
char **list;
list = calloc(n, MAX_STR*sizeof(char));
char *input;
int i;
for (i = 0; i < n; i++){
scanf("%s/n", input);
list[i] = input;
}
return list;
}
And this is the main function:
/*MAIN*/
int main(){
int linesnum = readlinesnum();
char **lines = linelist(linesnum);
char ***matrix = createmat(linesnum, lines);
char input;
fstruct ignore;
ignore.len = 0;
while (1){
scanf("%c", &input);
if (input == 'f'){
ignore = f(ignore);
}
else if (input == 's'){
s(lines, linesnum);
}
else if (input == 'l'){
l(matrix, lines, linesnum, ignore);
}
else if (input == 'w'){
w(matrix, lines, linesnum, ignore);
}
else if (input == 'h'){
h(matrix, linesnum);
}
else if (input == -1){
break;
}
}
freememory(matrix, lines);
return 0;
}
The readlinesnum function seems to be working fine, so it's when I actually get to creating the list with the lines that things don't go well. I'd love to understand the exact reason why they don't, for I think any other problems I surely have within the rest of the code are related to this issue as well.
Thank you.