memory management - Allocate a string array from inside a function in C -
i have function scans file , returns number of lines along lines in string array, function looks :
int load_lines(char* _file, char** _array){ file *infile; char line_buffer[bufsiz]; char line_number; infile = fopen(_file, "r"); ine_number = 0; while (fgets(line_buffer, sizeof(line_buffer), infile)) ++line_number; fclose(infile); _array = malloc (line_number * sizeof(char*)); infile = fopen(_file, "r"); line_number = 0; while (fgets(line_buffer, sizeof(line_buffer), infile)) { _array[line_number] = malloc(strlen(line_buffer) + 1); strcpy(_array[line_number], line_buffer); //a printf on _array[line_number] works fine here ++line_number; } return line_number; }
when call this:
char** _array; line_number = load_lines(inname, _array); _array[0];
i segmentation fault since array seems not allocated after return of function.
when pass argument function, function always works on copy of argument.
so in case, load_lines
working on copy of _array
. original _array
not modified:
char** _array = null; printf("%p\n", _array); // prints "0x0000" line_number = load_lines(inname, _array); printf("%p\n", _array); // prints "0x0000"
to modify _array
, need pass pointer it:
int load_lines(char* _file, char*** _array){ ... (*array) = malloc (line_number * sizeof(char*)); ... (*array)[line_number] = malloc(strlen(line_buffer) + 1); } char** _array = null; line_number = load_lines(inname, &_array);
[however, time find needing triple pointer (i.e. ***
), it's time reconsider architecture.]
Comments
Post a Comment