Your substr function returns a pointer to its local variable str. This automatic storage variable are discarded immediatly after return, so this pointer value is senseless one. The classical novice's error ;)
The second defect: you forgot to append terminated null byte at the end of the formed substring.
The 3rd defect: no parameters check at all (positions >= 0, pos1 <= pos2 etc) .
Of course, you can declare str as a static variable (bad solution: every substr call reuses the same static storage), or you can add yet another pointer parameter for extracted substring...
ArkM
Postaholic
2,001 posts since Jul 2008
Reputation Points: 1,234
Solved Threads: 348
No need in dest[i + 1] = '\0'; in the loop:
int i = 0, n = (endpos-startpos)+1;
if (dest && str && startpos >= 0) { // prevent future troubles!
if (startpos < strlen(str) && n > 0) {
str += startpos;
for (i = 0; i < n && str[i]; ++i) /* break if str ended! */
dest[i] = str[i];
}
dest[i] = '\0';
}
No need in printf "debug" statement in substr body.
No need in dynamic allocated memory in main (and you forgot to add 1 for null terminator).
ArkM
Postaholic
2,001 posts since Jul 2008
Reputation Points: 1,234
Solved Threads: 348