user2297642
user2297642

Reputation: 21

A redis command ERR:wrong number of arguments

using hiredis to pass the command to redis-server. My code:

redisContext* c = redisConnect("127.0.0.1", 6379);
char y[15]={"pointx"};
strcat(y," 2");

redisReply* reply= (redisReply*)redisCommand(c,"set %s",y);
printf("%s\n", reply->str);

The output is "ERR wrong number of arguments for 'set' command". However,it works when I change the code like this:

redisContext* c = redisConnect("127.0.0.1", 6379);
char y[15]={"pointx"};
char x[5] = {"2"};
redisReply* reply= (redisReply*)redisCommand(c,"set %s %s",y,x);
printf("%s\n", reply->str);

The output is "OK". why??

Upvotes: 2

Views: 8431

Answers (1)

Didier Spezia
Didier Spezia

Reputation: 73276

The Redis server does not parse the command built with redisCommand. The server only accepts Redis protocol, with already delimited parameters.

Parsing therefore occurs in hiredis, and it applies only on the format string, in one step. For performance reasons, hiredis avoids multiple formatting passes (or a recursive implementation), so expansion of the parameters is not done before parsing, but while parsing in on-going - contrary to what you think.

Imagine your objects are very big (say several MB), you would not want them to be parsed at each query. This is why hiredis only parses the format string and not the parameters.

In your first example, hiredis parses a format string with a unique parameter, it builds a message with only one parameter, and redis receives:

$ netcat -l -p 6379
*2
$3
set
$8
pointx 2

which is an ill formed set command (one parameter only).

Upvotes: 1

Related Questions