Hi all -
I'm just poking around with doing a few things in C without using library functions.
( I'm doing this to become more familiar with pointers (and now malloc). )
This code (to get a substring from a string) works fine, but I'm just wondering if I'm using malloc and free correctly.
Just trying to get comfortable with malloc and free, so confirmation that this code is Ok (or correction of it) would be good.Code:/* Return a substring from a string. */ /* This code is released to the public domain. */ /* "Share and enjoy...." ;) */ #include <stdio.h> #include <string.h> #include <ctype.h> #include <malloc.h> char *substr(char *str, int first, int last) { char *ret = malloc(80); int i; int j=0; for (i=first; i<last; i++) { ret[j] = str[i]; j++; } ret[j] = '\0' ; return ret; free(ret); } int main() { char *test = "averyverylongstringindeed"; printf("%s \n",substr(test,4,11) ); return 0; }
Thanks -
- trilobite
Bookmarks