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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
adnaan.zohran
  • 809
  • 9
  • 21
  • 1
    There is no need to cast the result of `malloc()` and friends, nor is recommended in any way to do so. – alk Jul 24 '15 at 11:58

2 Answers2

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.

mch
  • 9,424
  • 2
  • 28
  • 42
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.

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261