dynamic array of strings, but i get heap corruption detected

182 Views Asked by At

I try to make a dynamic array of char pointer, what means does pointers can be a dynamic memory too, so in the code above I try to allocate one size to the array and in him, allocate to the first object a string. But I get an error "heap corruption detected" on the array pointer.

int main(void)
{

    char** pArr = 0;
    char string[] = "hello";

    pArr = (char**)malloc(sizeof(char) * 1); //make it an array with one element
    *pArr = (char*)malloc(sizeof(char) * (strlen(string) + 1)); //make it an array with the size of string
    strcpy(*pArr, string); //copy string to the first element of the array

    printf("%p", pArr); //the pointer where the heap corruption is detected

    free(pArr);

    getchar();
    return 0;
}

I copied the whole main so you know I did nothing expect that.

1

There are 1 best solutions below

2
On

You don't allocate enough space here:

pArr = (char**)malloc(sizeof(char) * 1); 

You only allocate space for 1 char instead of 1 char *. So you end up writing past the end of allocated memory which invokes undefined behavior.

To allocate the correct amount of space:

pArr = malloc(sizeof(char *) * 1); 

Or better yet:

pArr = malloc(sizeof(*ptr) * 1);