Use std::string instead of malloc strings to make mbtiles metadata

This commit is contained in:
Eric Fischer
2016-04-28 11:56:30 -07:00
parent 40a6b7b37a
commit 3f0904cce8
+7 -21
View File
@@ -8,6 +8,7 @@
#include <string.h> #include <string.h>
#include <sqlite3.h> #include <sqlite3.h>
#include <vector> #include <vector>
#include <string>
#include "pool.hpp" #include "pool.hpp"
#include "mbtiles.hpp" #include "mbtiles.hpp"
#include "geometry.hpp" #include "geometry.hpp"
@@ -82,7 +83,7 @@ void mbtiles_write_tile(sqlite3 *outdb, int z, int tx, int ty, const char *data,
} }
} }
static void quote(char **buf, const char *s) { static void quote(std::string *buf, const char *s) {
char tmp[strlen(s) * 8 + 1]; char tmp[strlen(s) * 8 + 1];
char *out = tmp; char *out = tmp;
@@ -101,15 +102,10 @@ static void quote(char **buf, const char *s) {
} }
*out = '\0'; *out = '\0';
*buf = (char *) realloc(*buf, strlen(*buf) + strlen(tmp) + 1); buf->append(std::string(tmp));
if (*buf == NULL) {
perror("realloc");
exit(EXIT_FAILURE);
}
strcat(*buf, tmp);
} }
static void aprintf(char **buf, const char *format, ...) { static void aprintf(std::string *buf, const char *format, ...) {
va_list ap; va_list ap;
char *tmp; char *tmp;
@@ -120,12 +116,7 @@ static void aprintf(char **buf, const char *format, ...) {
} }
va_end(ap); va_end(ap);
*buf = (char *) realloc(*buf, strlen(*buf) + strlen(tmp) + 1); buf->append(std::string(tmp));
if (*buf == NULL) {
perror("Out of memory");
exit(EXIT_FAILURE);
}
strcat(*buf, tmp);
free(tmp); free(tmp);
} }
@@ -236,11 +227,7 @@ void mbtiles_write_metadata(sqlite3 *outdb, const char *fname, char **layername,
} }
sqlite3_free(sql); sqlite3_free(sql);
char *buf = strdup("{"); std::string buf("{");
if (buf == NULL) {
perror("Out of memory");
exit(EXIT_FAILURE);
}
aprintf(&buf, "\"vector_layers\": [ "); aprintf(&buf, "\"vector_layers\": [ ");
int i; int i;
@@ -291,7 +278,7 @@ void mbtiles_write_metadata(sqlite3 *outdb, const char *fname, char **layername,
aprintf(&buf, " ] }"); aprintf(&buf, " ] }");
sql = sqlite3_mprintf("INSERT INTO metadata (name, value) VALUES ('json', %Q);", buf); sql = sqlite3_mprintf("INSERT INTO metadata (name, value) VALUES ('json', %Q);", buf.c_str());
if (sqlite3_exec(outdb, sql, NULL, NULL, &err) != SQLITE_OK) { if (sqlite3_exec(outdb, sql, NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "set json: %s\n", err); fprintf(stderr, "set json: %s\n", err);
if (!forcetable) { if (!forcetable) {
@@ -299,7 +286,6 @@ void mbtiles_write_metadata(sqlite3 *outdb, const char *fname, char **layername,
} }
} }
sqlite3_free(sql); sqlite3_free(sql);
free(buf);
} }
void mbtiles_close(sqlite3 *outdb, char **argv) { void mbtiles_close(sqlite3 *outdb, char **argv) {