Reputation: 35
I am just learning C, Could someone explain why the following code produces a Segmentation fault after printing the first element of an array?
what would working code look like?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ELEMENTS 8
void make(char ***array) {
*array = malloc(ELEMENTS * sizeof(char *));
(*array)[0] = "test0";
(*array)[1] = "test1";
(*array)[2] = "test2";
(*array)[3] = "test3";
(*array)[4] = "test4";
(*array)[5] = "test5";
(*array)[6] = "test6";
(*array)[7] = "test7";
(*array)[8] = "test8";
}
int main(int argc, char **argv)
{
char **array;
make(&array);
int i;
for (i = 0; i < ELEMENTS; ++i) {
printf("%s\n", array[i]);
free(array[i]);
}
free(array);
return 0;
}
Upvotes: 0
Views: 138
Reputation: 765
When you put a literal string in C++ like "test0"
, it is actually stored in a special memory location where it cannot be modified. In the line
(*array)[0] = "test0";
you're pointing your char*
to that memory location, which is alright to do. However, later, when you call free(array[i]);
, you are attempting to free the same memory, which is a no-no. In general, only use free()
if you have previously used malloc()
on the same variable.
Also, as others have said, you need to allocate an array of size 9, since you're using 9 elements.
Upvotes: 0
Reputation: 44181
Your array size is 8
, but you access index 8
, which is one past the end of your array. Count the number of elements if you don't understand...
You call free
on the assigned string constants. Don't do this. Only free
what you malloc
, which is just array
, not array[0]
to array[8]
.
Upvotes: 6