1

I have an array of String (char **) which is initialised as NULL. After passing its address when I try to access its elements it gives segmentation fault.

//following code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


void parse(char ***test, char *str)
{
    int i;
    *test = (char**)malloc(sizeof(char*) * 3);
    for(i=0; i<3; i++)
    {
        *test[i] = (char*) malloc(sizeof(char)*(strlen(str)+1));
        strcpy(*test[i], str);
    }
}

int main(void)
{
    int i;
    char *str = "Hello world";
    char **test = NULL;
    parse(&test, str);
    for(i=0; i<3; i++)
        printf("%s\n", test[i]);
    return 0;
}

On using debugger inside the function parse all elements have correct values and properly initialised and allocated but from main function only 0 indexed row gives the correct value rest are segment fault.

1
  • 1
    There is no need to cast the result of malloc() and friends, nor is recommended in any way to do so. Commented Jul 24, 2015 at 11:58

2 Answers 2

4

*test[0] should be (*test)[i].

http://en.cppreference.com/w/c/language/operator_precedence says that [] has higher priority than *, which is not what you want.

You should also not overwrite the index 0.

sizeof(char) is always 1 and so you can leave it away. You should also not cast the return value of malloc and test for success.

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

1 Comment

This never struck me!! Amazing. Thanks a lot!
0

The problem here is

*test[0] = (char*) malloc(sizeof(char)*(strlen(str)+1));

you're always allocating memory to the index 0.

Also, following the operator precedence table, you need to dereference test first, then apply the idexing on that, so, you basically need to re-write your code like

(*test)[0]  = malloc( strlen(str) + 1);

Please note:

  1. See why not to cast the return value of malloc() and family in C.

  2. sizeof(char) is guranteed to produce 1. Multiplying by it is redundant.

1 Comment

that was a typo!! I have edited that!! Problem still persists!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.