Example
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
void dumpMem ( void *base, size_t len ) {
unsigned char *b = base;
printf("%p: ", base);
for ( size_t i = 0 ; i < len ; i++ ) {
printf("%02x ", b[i] );
}
printf("\n");
printf("%p: ", base);
for ( size_t i = 0 ; i < len ; i++ ) {
printf("%c ", isprint(b[i]) ? b[i] : '.');
}
printf("\n");
}
//Returns substring using given index
int retSubstring(char *myStr, size_t start, size_t end, char *subStri){
if(end > start){
char *s = &myStr[start];
char *e = &myStr[end + 1];
printf("_____before memcpy: '%s', size: %zd\n", subStri, e - s);
dumpMem(subStri-8,(e-s)+16); // the memory, and a bit around it
memcpy(subStri, s, e - s);
printf("_____after memcpy: '%s', size: %zd\n\n", subStri, e - s);
dumpMem(subStri-8,(e-s)+16); // the memory, and a bit around it
return 0;
}else{
printf("retSubstring error: end is greater than start.\n");
return 1;
}
}
int main(void){
int start = 8;
int end= 37;
char myStr[] = "1-2-1-2-1-2-1-2-1-2-1-2-1-2-1-2-1-2-1-2-1-2-1";
start = 0;
end= 10;
char * subStr2 = malloc(sizeof(char) * (end - start));
retSubstring(myStr, start, end, subStr2);
free(subStr2);
start = 20;
end= 25;
char * subStr3 = malloc(sizeof(char) * (end - start));
retSubstring(myStr, start, end, subStr3);
free(subStr3);
}
$ ./a.out
_____before memcpy: '', size: 11
0x1d21008: 21 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x1d21008: ! . . . . . . . . . . . . . . . . . . . . . . . . . .
_____after memcpy: '1-2-1-2-1-2', size: 11
0x1d21008: 21 00 00 00 00 00 00 00 31 2d 32 2d 31 2d 32 2d 31 2d 32 00 00 00 00 00 00 00 00
0x1d21008: ! . . . . . . . 1 - 2 - 1 - 2 - 1 - 2 . . . . . . . .
_____before memcpy: '', size: 6
0x1d21008: 21 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 31 2d 32 00 00 00
0x1d21008: ! . . . . . . . . . . . . . . . 1 - 2 . . .
_____after memcpy: '1-2-1-', size: 6
0x1d21008: 21 00 00 00 00 00 00 00 31 2d 32 2d 31 2d 00 00 31 2d 32 00 00 00
0x1d21008: ! . . . . . . . 1 - 2 - 1 - . . 1 - 2 . . .
Two things to note here:
1. The second malloc gets the same address as the first malloc, because you called free.
2. The second malloc cleaned out the memory from the previous use (though it's under no obligation to do so). Note that the amount cleared out is (on my system) rounded up to the next multiple of 8 bytes.
I suspect that if you tried your old code (using strlen) using end= 27; instead of 25 (so you have 8 bytes to copy), then you might just notice some weird stuff on other platforms as well.