Search code examples
cstringpointerssegmentation-faultpointer-to-pointer

segfault when setting character of malloced pointer-to-pointer string


In a bigger project i have been working on, i got an Segmentation fault (core dumped), so i managed to reproduce the problem like this:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {
    char **x = malloc(10 * 10);
    x[0][0] = 'a';

    printf("%s\n", x[0]);

    free(x);

    return 0;
}

Output: Segmentation fault (core dumped)

For some reason, (i don't know why) i get a Segmentation fault (core dumped) when i set a character in a pointer-to-pointer string (that is malloced)

Since the pointer is allocated on the heap, shouldn't i be able to change the array elements?

So i tried to initalize the array using memset like this:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {
    char **x = malloc(10 * 10);
    memset(x[0], 0x00, 10);
    x[0][0] = 'a';

    printf("%s", x[0]);

    free(x);

    return 0;
}

Output: Segmentation fault (core dumped)

Maybe i need to use strcpy?

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {
    char **x = malloc(10 * 10);
    strcpy(x[0], "Hi");

    printf("%s", x[0]);

    free(x);

    return 0;
}

Output: Segmentation fault (core dumped)

Okay maybe pointer-to-pointer just does not work even if it is on the heap.

What if it is a normal string?

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {
    char *x = malloc(10);
    x[0] = 'a';

    printf("%s\n", x);

    free(x);

    return 0;
}

Output: a

So why does a normal pointer work??

Maybe the internet will help.

Nevermind after i got bored before finding a single solution on the internet.

Can someone find a solution? Im not a genius at how C works so do forgive me if said something wrong.


Solution

  • In this line

    char **x = malloc(10 * 10);
    

    you are allocating an uninitialized array of char*.

    x[0][0] is dereferencing an uninitialized element x[0] of the array, so this will result in Segmentation Fault.

    You should allocate some buffer and assign that to the array before copying strings.

    Also don't forget to add terminating null-character to use the data as strings.

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    int main() {
        char **x = malloc(sizeof(*x) * 10);
        x[0] = malloc(10); /* allocate buffer and assign */
        x[0][0] = 'a';
        x[0][1] = '\0'; /* add terminating null-character */
    
        printf("%s\n", x[0]);
    
        free(x[0]);
        free(x);
    
        return 0;
    }