You allocated a place for 30 pointers, but you did not initialize them to point anywhere. If you did not declare the array outside the function, each element in the array will contain some random bit string, which may or may not correspond to a writable memory cell. If we drew a picture, it would look something like this (all addresses are out of thin air, donβt assume that this corresponds to any real architecture):
Item Address 0x00 0x01 0x02 0x03
---- ------- ---- ---- ---- ----
ptr 0xbbc81230 0x ?? 0x ?? 0x ?? 0x ??
0xbbc81234 0x ?? 0x ?? 0x ?? 0x ??
0xbbc81238 0x ?? 0x ?? 0x ?? 0x ??
...
0xbbc812a8 0x ?? 0x ?? 0x ?? 0x ??
where is 0x?? is a random byte value. For the described behavior, each of the random values ββsimply indicates a writable memory, and recording on top of what is stored there simply does not have any immediate side effects.
Bad juju: it looks like your code is working correctly when in fact it behaves very badly and can lead to some unpleasant run-time problems elsewhere in your program, which is a pain to debug.
You will need to explicitly set each element of the ptr array to indicate the correct memory location before attempting to register it.
Suppose we add the following code:
ptr[0] = malloc(strlen("foo") + 1); strcpy(ptr[0], "foo"); ptr[1] = malloc(strlen("bar") + 1); strcpy(ptr[1], "bar");
We dynamically allocated extra memory to hold several lines and saved pointers to these new buffers up to ptr[0] and ptr[1] .
Now our picture will look something like this:
Item Address 0x00 0x01 0x02 0x03
---- ------- ---- ---- ---- ----
0x80ff0000 'f' 'o' 'o' 0x00
...
0x80ffcdc0 'b' 'a' 'r' 0x00
...
ptr 0xbbc81230 0x80 0xff 0x00 0x00
0xbbc81234 0x80 0xff 0xcd 0xc0
0xbbc81238 0x ?? 0x ?? 0x ?? 0x ??
...
0xbbc812a8 0x ?? 0x ?? 0x ?? 0x ??
ptr[0] now contains the address of the buffer, whose size is 4 char , and we copy the string "foo" into this buffer. Similarly, ptr[1] contains the address of another 4-byte buffer, which now contains the string "bar".