nambvarun
nambvarun

Reputation: 1211

How to use calloc() in C?

Shouldn't I get an error if my string goes over 9 characters long in this program?

// CString.c
// 2.22.11

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

main()
{
    char *aString = calloc(10, sizeof(char));

    if (aString == NULL)
    {
        return 1;
    }

    printf("PLEASE ENTER A WORD: ");
    scanf("%s", aString);

    printf("YOU TYPED IN: %s\n", aString);
    //printf("STRING LENGTH: %i\n", strlen(aString));
}

Thanks

blargman

Upvotes: 3

Views: 10584

Answers (2)

Marlon
Marlon

Reputation: 20312

You don't get a compiler error because the syntax is correct. What is incorrect is the logic and, what you get is undefined behavior because you are writing into memory past the end of the buffer.

Why is it undefined behavior? Well, you didn't allocate that memory which means it doesn't belong to you -- you are intruding into an area that is closed off with caution tape. Consider if your program is using the memory directly after the buffer. You have now overwritten that memory because you overran your buffer.

Consider using a size specifier like this:

scanf("%9s", aString);

so you dont overrun your buffer.

Upvotes: 5

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215397

Yes, you got an error. And the most unfortunate part is that you don't know about it. You might know about it later on in the program when something mysteriously crashes (if you're lucky), or when your client's lawyers come to sue you (if you're not).

Upvotes: 1

Related Questions