Skip to content

Commit

Permalink
fix: delete memory allocated by 'new' before exiting
Browse files Browse the repository at this point in the history
  • Loading branch information
duruyao committed Mar 30, 2023
1 parent 691f200 commit ec5e3e4
Showing 1 changed file with 16 additions and 1 deletion.
17 changes: 16 additions & 1 deletion protobuf_rw_file.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -33,21 +33,30 @@ int main(int argc, char **argv) {
auto dataSize1 = fread(dataBuff1, sizeof(char), BUFF_SIZE, fp);
fclose(fp);
if (dataSize1 >= BUFF_SIZE) {
fprintf(stderr, "Error: file size greater than 16 MB: '%s'\n", argv[1]);
fprintf(stderr, "Error: file size is greater than 16 MB: '%s'\n", argv[1]);
delete[] dataBuff1;
return 1;
}

// assign values to the object pbFile1
PBFile pbFile1;
pbFile1.set_data_size(dataSize1);
pbFile1.set_data_buff(dataBuff1, dataSize1);
// printf("pbFile1.data_size(): %ld\n", pbFile1.data_size());
// printf("pbFile1.data_buff().size(): %ld\n", pbFile1.data_buff().size());
// printf("pbFile1.data_buff().length(): %ld\n", pbFile1.data_buff().length());
// printf("strlen(pbFile1.data_buff().c_str()): %ld\n", strlen(pbFile1.data_buff().c_str()));

// serialize the object pbFile1 to a string
auto serializedStr = pbFile1.SerializeAsString();

// deserialize a string to the object pbFile2
PBFile pbFile2;
pbFile2.ParseFromString(serializedStr);
// printf("pbFile2.data_size(): %ld\n", pbFile2.data_size());
// printf("pbFile2.data_buff().size(): %ld\n", pbFile2.data_buff().size());
// printf("pbFile2.data_buff().length(): %ld\n", pbFile2.data_buff().length());
// printf("strlen(pbFile2.data_buff().c_str()): %ld\n", strlen(pbFile2.data_buff().c_str()));

// read data from pbFile2 to a buffer
char *dataBuff2 = new char[BUFF_SIZE];
Expand All @@ -57,16 +66,22 @@ int main(int argc, char **argv) {
// compare dataBuff1 with dataBuff2
if (0 != memcmp(dataBuff1, dataBuff2, dataSize2)) {
fprintf(stderr, "Error: dataBuff1 != dataBuff2\n");
delete[] dataBuff1;
delete[] dataBuff2;
return 1;
}

// write data from a buffer to a binary file
if (nullptr == (fp = fopen(argv[2], "wb"))) {
fprintf(stderr, "Error: cannot open file: '%s'\n", argv[2]);
delete[] dataBuff1;
delete[] dataBuff2;
return 1;
}
fwrite(dataBuff2, sizeof(char), dataSize2, fp);
fclose(fp);

delete[] dataBuff1;
delete[] dataBuff2;
return 0;
}

0 comments on commit ec5e3e4

Please sign in to comment.