0

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;

}

1
  • 1
    Actually, you need to read a lot about punters, just google it, you'll information to get fun... Commented Apr 5, 2013 at 13:35

2 Answers 2

5
  1. 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...

  2. 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].

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.