0

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 Answers1

1

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); 
dbush
  • 162,826
  • 18
  • 167
  • 209
  • 1
    yeah you right, so the pointers have their own size thanks for the lesson! – Artur Karabekov May 19 '20 at 12:47
  • @ArturKarabekov Glad I could help. Feel free to [accept this answer](https://stackoverflow.com/help/accepted-answer) if you found it useful. – dbush May 19 '20 at 12:48