Before starting the cycle, dp indicates the beginning of the allocated memory. At each iteration, you copy the character indicated by src to the current dp position and go to one memory location that dp points to. At the end of the loop, dp points to the memory location immediately after the p character, where you assigned '\0' . When you try to print a line using puts (dp) because the contents of dp changed and now point to the location immediately after copying the last character, it will start printing from that place. It will print an empty line, since the very first location dp points to is a null character.
Before the cycle
+----------+ | src | +----------+ | | V +-----+-----+-----+-----+-----+-----+-----+---- ----+----+ | h | t | t | p | : | / | / | . . . ? | ? | +-----+-----+-----+-----+-----+-----+-----+---- ----+----+ +----------+ | dp | +----------+ | | V +-----+-----+-----+-----+-----+-----+-----+---- ----+----+ | | | | | | | | . . . | | +-----+-----+-----+-----+-----+-----+-----+---- ----+----+
After the loop (with dp = malloc (10))
+----------+ | src | +----------+ | | V +-----+-----+-----+-----+-----+-----+-----+---- ----+----+ | h | t | t | p | : | / | / | . . . | ? | +-----+-----+-----+-----+-----+-----+-----+---- ----+----+ +----------+ | dp | +----------+ | | V +-----+-----+-----+-----+-----+-----+-----+---- ----+----+ | h | t | t | p | \0 | | | . . . | | +-----+-----+-----+-----+-----+-----+-----+---- ----+----+
Note puts (dp) will start printing print from the above location. This will not give the expected result. Also, since you did not save the original dp address that you actually allocated. You cannot recover from a cycle.
After the loop (with dp = & circuit)
+----------+ | src | +----------+ | | V +-----+-----+-----+-----+-----+-----+-----+---- ----+----+ | h | t | t | p | : | / | / | . . . | ? | +-----+-----+-----+-----+-----+-----+-----+---- ----+----+ +----------+ | dp | +----------+ | | V +-----+-----+-----+-----+-----+-----+-----+---- ----+----+ scheme[ | h | t | t | p | \0 | | | . . . | | ] +-----+-----+-----+-----+-----+-----+-----+---- ----+----+ puts (scheme) will work because it still refers to the base of the array puts (dp) will not work because it does not point to the base of the array and currently points to a location pointing to null character
The above commented solution works because you use the scheme array to print the string. scheme refers to the array you want to print, and scheme refers to the base address of the array because you did not modify it (and you cannot change it). That's why it starts from the base and prints to the '\0' that you assigned after the loop.
You can either do
int i; for (i=0; (src[i] != ':') && (src[i] != '\0'); i++) { dp[i] = src[i]; }
or follow below
char *dp_bak; char *dp = malloc(10); dp_bak = dp; while (*src != ':') { *dp = *src; src++; dp++; } *dp = '\0'; dp = db_bak; puts (dp);
source share