Allocating string with malloc

malloc() returns a void* pointer to a block of memory stored in the heap. Allocating with malloc() does not initialize any string, only space waiting to be occupied.To add a null-terminating character, you either have to do this yourself, or use a function like scanf(), which adds this character for you. Having said this, you need to allocate space for this \0 character beforehand.

Your malloc() call should be this instead:

stringa1 = (char*) malloc((n+1)*sizeof(char)); /*+1 for '\0' character */

Note: You don’t need to cast return of malloc. For more information, read this.

Another thing to point out is sizeof(char) is 1, so multiplying this in your malloc() call is not necessary.

You also need to check if malloc() returns NULL. This can be done like this:

if (stringa1 == NULL) {
    /* handle exit */

Also, you can only use strlen() on a null-terminated string, otherwise this ends up being undefined behaviour.

Once scanf() is called, and the stringa1 contains some characters, you can call strlen() on it.

Additionally, checking return of scanf() is also a good idea. You can check it like this:

if (scanf("%d", &n) != 1) {
    /* handle exit */

Your code with these changes:

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

int main(void) {
    char *stringa1 = NULL;
    size_t n, slen;

    printf("How many characters in the string? ");
    if (scanf("%zu", &n) != 1) {
        printf("Invalid input\n");
        exit(EXIT_FAILURE);
    }

    stringa1 = malloc(n+1);
    if (stringa1 == NULL) {
        printf("Cannot allocate %zu bytes for string\n", n+1);
        exit(EXIT_FAILURE);
    }

    printf("Insert the string: ");
    scanf("%s", stringa1);

    slen = strlen(stringa1);
    printf("String: %s Length: %zu\n", stringa1, slen);

    free(stringa1);
    stringa1 = NULL;

    return 0;
}

Leave a Comment