Permalink
Browse files

[api] Handle `realloc` errors

  • Loading branch information...
1 parent 1a0313e commit 2339f59c5bafc2b48d4a991bb034d92ef83e990f @mmalecki committed Mar 30, 2013
Showing with 15 additions and 5 deletions.
  1. +2 −1 include/saneopt.h
  2. +11 −2 src/saneopt.c
  3. +2 −2 test/test-saneopt.c
View
@@ -21,8 +21,9 @@ saneopt_t* saneopt_init(int argc, char** argv);
/*
* Set an alias from `option` to `alias`.
+ * Return -1 on error, 0 on success.
*/
-void saneopt_alias(saneopt_t* opt, char* option, char* alias);
+int saneopt_alias(saneopt_t* opt, char* option, char* alias);
/*
* Get option called `option`.
View
@@ -50,16 +50,25 @@ int saneopt__matches(saneopt_t* opt, char* option, char* arg) {
return 0;
}
-void saneopt_alias(saneopt_t* opt, char* option, char* alias) {
+int saneopt_alias(saneopt_t* opt, char* option, char* alias) {
+ saneopt__alias_t** aliases;
saneopt__alias_t* alias_ = malloc(sizeof(saneopt__alias_t));
+
alias_->option = option;
alias_->alias = alias;
- opt->aliases = realloc(
+ aliases = realloc(
opt->aliases,
++opt->alias_count * sizeof(saneopt__alias_t*)
);
+
+ if (aliases == NULL)
+ return -1;
+
+ opt->aliases = aliases;
opt->aliases[opt->alias_count - 1] = alias_;
+
+ return 0;
}
char* saneopt_get(saneopt_t* opt, char* option) {
View
@@ -62,7 +62,7 @@ void test_long_alias() {
argv[2] = "value";
saneopt_t* opt = saneopt_init(3, argv);
- saneopt_alias(opt, "option", "alias");
+ assert(saneopt_alias(opt, "option", "alias") == 0);
assert(strcmp(saneopt_get(opt, "option"), "value") == 0);
free(argv);
@@ -78,7 +78,7 @@ void test_short_alias() {
argv[1] = "value";
saneopt_t* opt = saneopt_init(2, argv);
- saneopt_alias(opt, "option", "o");
+ assert(saneopt_alias(opt, "option", "o") == 0);
assert(strcmp(saneopt_get(opt, "option"), "value") == 0);
free(argv);

0 comments on commit 2339f59

Please sign in to comment.