Reputation: 13
This is what my main functions looks like. This cannot be changed as it is being used in the file my professor is using to grade the assignment.
char** lines = NULL;
int line_count = 5;
add_lines(&lines, line_count);
In this function, I need to dynamically allocate the lines
array and store multiple strings inside. The memory is then being freed in main. This is how I am currently doing it, but I keep getting a segfault. (This function also must take a char***
).
void add_lines(char*** lines, int line_count) {
*lines = (char**)malloc(line_count*sizeof(char*));
for (int i = 0; i < line_count; i++)
*lines[i] = (char*)malloc(64*sizeof(char));
}
I am assuming this error has to do with dereferencing and trying to dynamically allocate a NULL pointer, but I'm not sure how I'd go about fixing it.
Upvotes: 0
Views: 82
Reputation: 225757
This line isn't doing what you think:
*lines[i] = (char*)malloc(64*sizeof(char));
The array index operator []
has higher precedence than the unary dereference operator *
. So it attempts to access lines
as an array (which it isn't), then dereference the array member. This ends up working when i
is 0 because it will point to the first allocated array element, but when i
is larger you access memory past lines
in the calling function.
You need to use parenthesis to make sure you dereference lines
first, then index the array elements.
(*lines)[i] = malloc(64*sizeof(char));
Also, don't cast the return value of malloc
. It's unnecessary and can mask subtle bugs.
Upvotes: 2