diff --git a/main/pbx.c b/main/pbx.c
index c13feffb7b2e66ffb5d5e3e89d6c005ff408dfd9..3b3b1cd6db508e2f6e4cd2ff09310aed02123314 100644
--- a/main/pbx.c
+++ b/main/pbx.c
@@ -9434,14 +9434,15 @@ int pbx_builtin_setvar_helper(struct ast_channel *chan, const char *name, const
 			nametail++;
 	}
 
-	AST_LIST_TRAVERSE (headp, newvariable, entries) {
+	AST_LIST_TRAVERSE_SAFE_BEGIN(headp, newvariable, entries) {
 		if (strcasecmp(ast_var_name(newvariable), nametail) == 0) {
 			/* there is already such a variable, delete it */
-			AST_LIST_REMOVE(headp, newvariable, entries);
+			AST_LIST_REMOVE_CURRENT(entries);
 			ast_var_delete(newvariable);
 			break;
 		}
 	}
+	AST_LIST_TRAVERSE_SAFE_END;
 
 	if (value) {
 		if (headp == &globals)