diff --git a/libavfilter/avfiltergraph.c b/libavfilter/avfiltergraph.c
index af96807531d46046592bc4ff5e6ef1ce623608ba..b7dce7576fa9d14b265221bd3cc89c1450cb37ef 100644
--- a/libavfilter/avfiltergraph.c
+++ b/libavfilter/avfiltergraph.c
@@ -23,6 +23,7 @@
 #include <ctype.h>
 #include <string.h>
 
+#include "libavutil/avstring.h"
 #include "avfilter.h"
 #include "avfiltergraph.h"
 #include "internal.h"
@@ -163,7 +164,11 @@ static int query_formats(AVFilterGraph *graph, AVClass *log_ctx)
                     /* couldn't merge format lists. auto-insert scale filter */
                     snprintf(inst_name, sizeof(inst_name), "auto-inserted scaler %d",
                              scaler_count++);
-                    snprintf(scale_args, sizeof(scale_args), "0:0:%s", graph->scale_sws_opts);
+                    av_strlcpy(scale_args, "0:0", sizeof(scale_args));
+                    if (graph->scale_sws_opts) {
+                        av_strlcat(scale_args, ":", sizeof(scale_args));
+                        av_strlcat(scale_args, graph->scale_sws_opts, sizeof(scale_args));
+                    }
                     if ((ret = avfilter_graph_create_filter(&scale, avfilter_get_by_name("scale"),
                                                             inst_name, scale_args, NULL, graph)) < 0)
                         return ret;
diff --git a/libavfilter/graphparser.c b/libavfilter/graphparser.c
index 00fb57ad5764efef7b56c59e9d1fa0f438e2c88f..0678cd0b3515d811bd64e9c376f2fbe1228463b6 100644
--- a/libavfilter/graphparser.c
+++ b/libavfilter/graphparser.c
@@ -121,7 +121,8 @@ static int create_filter(AVFilterContext **filt_ctx, AVFilterGraph *ctx, int ind
         return ret;
     }
 
-    if (!strcmp(filt_name, "scale") && args && !strstr(args, "flags")) {
+    if (!strcmp(filt_name, "scale") && args && !strstr(args, "flags") &&
+        ctx->scale_sws_opts) {
         snprintf(tmp_args, sizeof(tmp_args), "%s:%s",
                  args, ctx->scale_sws_opts);
         args = tmp_args;