i trying return array of string function , free memory used. code below:
int main(int argc, const char * argv[]) { (int m = 0; m < 10000; m++) { char **data = datatest(); int = 0; while(data[i]) { printf("%p ",data[i]); free(data[i]); i++; } printf(" address= %p.\n",data); free(data); } return 0; } here function:
char **datatest() { char *row[] = {"this", "is", "a", "data", "string", null}; char **str = row; char **datareturn = (char **) malloc(sizeof(char *) * 6); int = 0; while (*str) { datareturn[i] = malloc(sizeof(char) * strlen(*str)); strcpy(datareturn[i++], *str); str++; } return datareturn; } it runs in beginning, error occurs. below result. address goes wrong somehow , malloc error happens. has met same problem before?
0x100300030 0x100300040 0x100300050 0x100300060 0x100300070 address= 0x100300000. 0x100300030 0x100300040 0x100300050 0x100300060 0x100300070 address= 0x100300000. 0x100400030 0x100300030 0x100300040 0x100300050 0x100300060 address= 0x100400000. testc(562,0x7fff73e71310) malloc: *** error object 0x3000000000000: pointer being freed not allocated *** set breakpoint in malloc_error_break debug 0x100300060 0x100300070 0x100300030 0x100300040 0x100300050 0x3000000000000 program ended exit code: 9
you need add before return datareturn; in datatest function:
datareturn[i] = null ; otherwise while (data[i]) {} continue further wanted.
and instead of:
datareturn[i] = malloc( sizeof(char) * (strlen(*str)) ); write:
datareturn[i] = malloc(strlen(*str) + 1); in order allocate space terminating zero.
btw sizeof (char) 1.
Comments
Post a Comment