joaomlap
joaomlap

Reputation: 335

C: Why does snprintf only writes 4 characters to my variable?

So I'm trying to return a variable that contains a string with some parameters determined inside the function.

char* render(my parameters)

I'm declaring my variable like this:

char *string = malloc(sizeof(char) * 50);

This is an excerpt of my function:

switch(INST_OPCODE){
        case 0x00:
            inst->name = malloc(sizeof(char) * (strlen("add") + 1));
            inst->name = "add";
            inst->type = 1;
            snprintf(string, sizeof(string), "add r%d, r%d, r%d", INST_RD, INST_RA, INST_TYPE_A_RB);
            printf("add r%d, r%d, r%d", INST_RD, INST_RA, INST_TYPE_A_RB);
            return string;
        case 0x01:
            inst->name = malloc(sizeof(char) * (strlen("rsub") + 1));
            inst->name = "rsub";
            inst->type = 1;
            snprintf(string, sizeof(string), "rsub r%d, r%d, r%d", INST_RD, INST_RA, INST_TYPE_A_RB);
            printf("rsub r%d, r%d, r%d", INST_RD, INST_RA, INST_TYPE_A_RB);
            return string;

The printf works fine and it's just for debugging purposes, but when I print the returned variable in a file with:

fprintf(fd, "%s\n", render(my parameters));

It writes only 4 characters and then literally memory garbage, one example:

addi-ž

Please give me some insight of what's going on here.

Upvotes: 0

Views: 306

Answers (2)

user4413591
user4413591

Reputation:

4 is the size of the pointer on 32 bit systems, it's 8 on 64 bit systems. For pointers, sizeof always return the size of the pointer and not the size of the data it points to.

Better yet, use sizeof(char) * num_characters_in_string. Use sizeof(char) * 50 in this case.

Of course, sizeof(char) always equals 1, so you can omit that part if you want.

The reason you get garbage is because some data is not initialized (due to the size parameter). Debuggers automatically initialize everthing to 0, so that is why it would work while debugging. Outside of debugging, it can start with any value.

Finally, the printf statement works because you didn't print out your return value. It might've been more prudent to write printf("%s", string); rather than repeat your snprintf line. (Remember -- snprintf only printed up to n characters, so the rest of the characters were left with their garbage values).

Upvotes: 1

Steve Summit
Steve Summit

Reputation: 48000

In your case the second argument to snprintf needs to be 50, not sizeof(string).

Upvotes: 2

Related Questions