cstringsegmentation-fault

Assigning character in array of strings segmentation fault in C


Very confused on why I'm getting a "Segmentation Fault (core dumped)".

const int bufSize = 32;
char* splitStrings[bufSize];
splitStrings[0][0] = 'a';
splitStrings[0][1] = '\0';
printf("testchar: %c",splitStrings[0][0]);
printf("teststr: %s",splitStrings[0]);

Thanks for any help


Solution

  • I think you want to define a 2-D array with char elements.

    To do this make these steps:

    First

    Define a char** array of pointers.

    char **splitStrings[bufSize];
    

    Second

    Allocate memory for row:

    splitStrings = malloc(bufSize*sizeof(char*));
    

    Third

    For each row allocate memory for its columns.

    for (int i=0;i<bufSize;i++){
       splitStrings[i]=malloc(bufSize*sizeof(char*));
    }
    

    Code

    #include <stdio.h>///for printf()
    #include <stdlib.h>///for malloc()
    
    int main(void){
    
        const int bufSize = 32;
        char **splitStrings;
    
        splitStrings = malloc(bufSize*sizeof(char*));
    
        for (int i=0;i<bufSize;i++){
            splitStrings[i]=malloc(bufSize*sizeof(char*));
        }
    
        splitStrings[0][0] = 'a';
        splitStrings[0][1] = '\0';
    
        printf("testchar: %c\n", splitStrings[0][0]);
        printf("teststr: %s\n", splitStrings[0]);
        
        free(splitStrings);
    
        return 0;
    }
    

    Further Notes

    malloc manpage error section

    ERRORS calloc(), malloc(), realloc(), and reallocarray() can fail with the following error:

       ENOMEM Out of memory.  Possibly, the application hit  the  RLIMIT_AS
              or RLIMIT_DATA limit described in getrlimit(2).
    

    Last Edition on code

    Change malloc(bufSize*sizeof(char)); to malloc(bufSize*sizeof(char*)); this is true way of allocating memory

    Because in first case calling free() on splitStrings pointer cause memory error. Why?