qiubit
qiubit

Reputation: 4806

C - SIGSEGV after accessing malloc'ed memory

Here's a snippet of code that causes segmentation fault:

void test_list(char **list)
{
    *list = malloc (100 * sizeof(char));
    *list[0] = 't';
    *list[1] = 'e'; // SIGSEGV here
    *list[2] = 's';
    *list[3] = 't';
}

int main()
{
    char *list;
    test_list(&list);
    return 0;
}

What has just happened?

Upvotes: 0

Views: 55

Answers (1)

Paul R
Paul R

Reputation: 212939

Beware of operator precedence - change:

*list[0] = 't';

to

(*list)[0] = 't';

(and so on...)

Upvotes: 3

Related Questions