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.
You don't allocate enough space here:
You only allocate space for 1
char
instead of 1char *
. So you end up writing past the end of allocated memory which invokes undefined behavior.To allocate the correct amount of space:
Or better yet: