Trotten
Trotten

Reputation: 63

create string with calloc

I'm trying to create a string with a simply calloc, but i don't understand why this code works. This calloc would have to create a string with only one space to put only a char, right? Why, when i try to print my string, on stdout i see value casted to string? I thought on stdout appeared only the first number, because I have allocated with calloc only one space.

int main(int argc, const char* argv[]) {
    char* string;
    int value=6000031;
    string=calloc(1,sizeof(char));
    sprintf(string,"%d",value);
    printf("%s\n",string);
    free(string);
    exit(EXIT_SUCCESS);
}

Upvotes: -1

Views: 9700

Answers (1)

ryry1985
ryry1985

Reputation: 336

sprintf will try to write the whole value to the string array. It doesn't know the size of the memory. You end up writing into invalid memory. It just so happens you're not causing a seg fault.

Use snprintf with a size of 1, but it would always return an empty string in that case. If you are just trying to pull off the first character, use snprintf(string, 2, "%d", value); and increase the calloc size to 2 bytes. (One for the NUL character at the end)

Upvotes: 5

Related Questions