Could a void pointer store a larger array than its dynamically allocated size?
Pointers of any pointer type store addresses. Pointers themselves have a size determined by their (pointer) type, like any other object, and it's very common for all pointers provided by a given implementation to have the same size as each other. If you allocate memory, then the size is a characteristic of the allocated object, not of any pointer to it.
I was not expecting it to work because the void pointer is only given 2 bytes which is not enough for my 23 byte char array.
Indeed the two bytes you allocated are not enough to accommodate the 24 bytes of your string literal (don't forget to count the string terminator), but
That's irrelevant, because you don't attempt to use the allocated space. Assigning to a pointer changes the value of the pointer itself, not of whatever data, if any, it points to.
Even if you were modifying the pointed-to data, via strcpy()
, for example, C does not guarantee that it would fail. Instead, such an attempt would produce undefined behavior, which could manifest in any way at all that is within the power of the program and C implementation. Sometimes that even takes the appearance of what the programmer wanted or supposed.
How did my void pointer exceed the size I initially requested?
It did not. You allocated two bytes, and recorded a pointer to their location in p
. Then, you assigned the address of the first character of your string literal to p
, replacing its previous value. The contents of the string literal are not copied. The program no longer having a pointer to the allocated two bytes, it has no way to access them or free them, but deallocating them requires calling free
, so they remain allocated until the program terminates. This is called a "memory leak".
I should furthermore point out that there is a special consideration here involving string literals. These represent arrays, and in most contexts where an array-valued expression appears in C source code, the array is converted automatically to a pointer to its first element. A popular term for that is that arrays decay to pointers. This is why you end up assigning p
to point to the first character of the array. The same would not apply if you were assigning, say, an int
or double
value to p
, and your compiler indeed ought at least to warn in such cases.