Hi,
With concern of buffer overflow, memory leaks and/or having invalid pointer issue, change of pointer to garbage etc.
I didn't use realloc & strcat to avoid such problem in this program.
Would like to know from experts, how well the below program work on memory management?
Code:
int main()
{
FILE *indexfile;
indexfile = fopen("supermarket.osm", "a");
char *file_header="<osm version=\"0.6\" generator=\"osmconvert 0.8.3\">\n";
char *first_line = "<node id=\"\" lat=\"\" lon=\"\">\n";
char *second_line = "<tag k=\"name\" v=\"\"/>\n";
char *third_line = "<tag k=\"addr:city\" v=\"\"/>\n";
char *fourth_line = "<tag k=\"addr:street\" v=\"\"/>\n";
char *fifth_line = "<tag k=\"addr:housenumber\" v=\"\"/>\n";
char *last_line = "</node>\n";
int node_id=1;
char *tagvl = "nah und frisch";
char *cityvl = "Schönberg";
char *add_street = "Große Mühlenstraße";
double lat = 54.3884, lon = 10.38285;
char *housenr = "100";
char *spnt_temp_1st_line = NULL;
char *spnt_temp_2nd_line = NULL;
char *spnt_temp_3rd_line = NULL;
char *spnt_temp_4th_line = NULL;
char *spnt_temp_5th_line = NULL;
char *spnt_temp_6th_line = NULL;
spnt_temp_1st_line = (char *) malloc(17 + sizeof(char*) * (strlen(first_line)));
sprintf(spnt_temp_1st_line," <node id=\"%d\" lat=\"%1.7f\" lon=\"%1.7f\">\n",
node_id,lat,lon);
spnt_temp_2nd_line = (char *) malloc(3 +
sizeof(char*) * (strlen(second_line) + strlen(tagvl)));
sprintf(spnt_temp_2nd_line," <tag k=\"name\" v=\"%s\"/>\n",tagvl);
spnt_temp_3rd_line = (char *) malloc(3 +
sizeof(char*) * (strlen(third_line) + strlen(cityvl)));
sprintf(spnt_temp_3rd_line," <tag k=\"addr:city\" v=\"%s\"/>\n",cityvl);
spnt_temp_4th_line = (char *) malloc(3 +
sizeof(char*) * (strlen(fourth_line) + strlen(add_street)));
sprintf(spnt_temp_4th_line," <tag k=\"addr:street\" v=\"%s\"/>\n",add_street);
spnt_temp_5th_line = (char *) malloc(3 +
sizeof(char*) * (strlen(fifth_line) + strlen(housenr)));
sprintf(spnt_temp_5th_line," <tag k=\"addr:housenumber\" v=\"%s\"/>\n",housenr);
spnt_temp_6th_line = (char *) malloc(2 +
sizeof(char*) * (strlen(last_line)));
sprintf(spnt_temp_6th_line," </node>\n");
char *file_string;
file_string = (char *) malloc(1 + sizeof(char*) *(strlen(file_header) +
strlen(spnt_temp_1st_line) +
strlen(spnt_temp_2nd_line) +
strlen(spnt_temp_3rd_line) +
strlen(spnt_temp_4th_line) +
strlen(spnt_temp_5th_line) +
strlen(spnt_temp_6th_line)));
sprintf(file_string,"%s%s%s%s%s%s%s</osm>\n",file_header,
spnt_temp_1st_line,spnt_temp_2nd_line,
spnt_temp_3rd_line,spnt_temp_4th_line,
spnt_temp_5th_line,spnt_temp_6th_line);
printf("%s",file_string);
fputs(file_string,indexfile);
//free all malloc
free(spnt_temp_1st_line);
free(spnt_temp_2nd_line);
free(spnt_temp_3rd_line);
free(spnt_temp_4th_line);
free(spnt_temp_5th_line);
free(spnt_temp_6th_line);
free(file_string);
return 0;
}
Thanks.