user3021370
user3021370

Reputation: 61

Dynamic 2D char array

I want to allocate my 2D char array dynamically. Here I try to do this in cycle, but it gets me segmentation fault error. If I remove "arr[length] = str;" it will be ok. But it's not what I want to do.

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

int main(void) {
    char** arr;
    int i = 0;
    int length = 0;
    for(i = 0; i < 4; i ++) {
        arr = (char**) realloc(arr, (length+1) * sizeof(char*));
        char* str = (char*) malloc(4 * sizeof(char));
        arr[length] = str;
    }

    return 0;
}

Upvotes: 1

Views: 537

Answers (3)

Lan Pac
Lan Pac

Reputation: 375

You can do what Guido said but you can instead also set initially

char** arr = NULL;

because when realloc gets a NULL pointer as input it behaves as malloc.

Also the loop i assume must be

for(i = 0; i < 4; i ++) {
     arr = (char**) realloc(arr, (length+1) * sizeof(char*));
     char* str = (char*) malloc(4 * sizeof(char));
     arr[length++] = str;
}

Notice the length++.

Upvotes: 3

Michael
Michael

Reputation: 1503

According to manual:

The realloc() function changes the size of the memory block pointed to by ptr to size bytes. The contents will be unchanged in the range from the start of the region up to the minimum of the old and new sizes. If the new size is larger than the old size, the added memory will not be initialized. If ptr is NULL, then the call is equivalent to malloc(size), for all values of size; if size is equal to zero, and ptr is not NULL, then the call is equivalent to free(ptr). Unless ptr is NULL, it must have been returned by an earlier call to malloc(), calloc() or realloc(). If the area pointed to was moved, a free(ptr) is done.

So, to use realloc() you should pass NULL pointer at first call to it. Thus, arr should be initialized to NULL.

Upvotes: 0

Guido
Guido

Reputation: 2634

You're using realloc on a arr, but you never allocated space for it. Use malloc

Upvotes: 0

Related Questions