How to use calloc () in C?

Should I get an error if my string contains more than 9 characters 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));
}

thank

blargman

+3
source share
2 answers

You are not getting a compiler error because the syntax is correct. What is wrong is the logic and what you get is undefined behavior because you are writing to memory at the end of the buffer.

Why is this behavior undefined? Well, you did not allocate this memory, which means that it does not belong to you - you are invading an area that is closed with caution tape. Think about whether your program uses memory immediately after the buffer. You overwrote this memory because you overloaded your buffer.

:

scanf("%9s", aString);

.

+6

, . , . , - ( ), - , ( ).

+1

Source: https://habr.com/ru/post/1794323/


All Articles