The function is intended to form real numbers from an array of arrays (the program receives all data as a text file from which it must create an array of structures) using pointers to a part of the string. After debugging using the console, a memory problem was discovered. First, after the end of the line (the current_star variable), it contained some more garbage, and secondly, a memory overflow occurred. Please help me figure it out. Thank you in advance!
float *arrayCreate(char *str_data, float *bstars, int *k) { char *current_star = NULL, *cur_star_end; //current star size as a string int i = 0, sum = 0; bstars = NULL; cur_star_end = str_data; while (cur_star_end!=NULL) { cur_star_end = strchr(str_data, ' '); if (cur_star_end!=NULL) { current_star = (char*)realloc(current_star, sizeof(char)*(cur_star_end-str_data+1)); strncpy(current_star, str_data, cur_star_end-str_data); } else { current_star = (char*)realloc(current_star, sizeof(char)); strcpy(current_star, str_data); } if (strlen(current_star)!=1) { bstars = (float*)realloc(bstars, sizeof(float)*(i+1)); bstars[i] = atof(current_star); sum += bstars[i]; i++; if (cur_star_end!=NULL) str_data = cur_star_end+1; } } *k = i; free(current_star); current_star = NULL; free(str_data); str_data = NULL; return bstars; }
char *current_star = malloc(1);This is for starters .. `bstars` also ... Not bad results for alok to check, you never know .. - NewViewreallocfunction perfectly knows how to work with a null pointer on an input. It is equivalent tomallocin this case. Using null at the start is an elegant and well-established pattern usingrealloc. Do not turn it into a terrible and uselessmalloc(1). - AnT 6:51 pm