#include <stdio.h>
#include <stdlib.h>
int main(int argc, char * argv[])
{
char *p[2];
char **pp = calloc(2, 4);
p[0] = "ab";
p[1] = "cd";
// p[2] = "ef";
pp[0] = "ab";
pp[1] = "cd";
pp[2] = "ef";
printf("pp: %s, %s, %s\n", pp[0], pp[1], pp[2]);
printf("size_p: %d\nsize_pp: %d\n", sizeof p, sizeof pp);
}
if ‘p[2]’ is defined and assigned a value – the resulting behavior is a segfault. if ‘pp[2]’ is assigned – the output is the following: “ab, cd, ef”. ‘sizeof’ returns 8 (2×4 bytes per pointer) for ‘p’ and only 4 bytes for ‘pp’. why am i being able to assign ‘pp[2]’, even though it should only be in possession of 8 bytes of allocated memory (that should be able to store only 2 pointer addresses)? also, how does ‘sizeof’ determine the actual memory size in both of the cases?
With
char *p[2];you allocate 2char*on the stack. When accessingp[2], you have a buffer overflow and might access any other fings belonging to the stack frame of the current method (some compilers check this in debug mode).With
calloc, you allocate memory in the heap. Accessingpp[2]is (probabely) free memory, you no segfault here. But this memory could also be used by other objects, so this is absolutely not ok!For size calculation:
sizeof(char**)is 4, as is for every 32-bit pointer.sizeof(char*[2])is 8, because it is 2×4 bytes.