gatsbyz
gatsbyz

Reputation: 1075

What is wrong with this code? (Basic C Code)

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

int main(int argc, char *argv[])
{
    char *a = "kitty";
    const int a_length = strlen(a);

    char *my_kitty = malloc(a_length);

    strcpy(my_kitty, a);

    printf("%s\n", my_kitty);

    return EXIT_SUCCESS;
}

What is wrong with this code? Null check for malloc? I am kind of confused about pointers.

Upvotes: 0

Views: 417

Answers (4)

StuartLC
StuartLC

Reputation: 107237

Don't forget to allocate an extra +1 for the null terminator!

char *my_kitty = malloc(a_length + 1);
... strcpy()

my_kitty[a_length] = 0;

(as per the comments, strcpy will also copy the null terminator)

Edit

Just be careful when using either strcpy or strncpy - the former is prone to buffer overflows if the null terminator is omitted, and the latter, although safer in the sense that it will limit the number of copied characters, will omit the null terminator if there is insufficient length remaining.

Upvotes: 2

hdante
hdante

Reputation: 8020

You allocated space for the text part of the string, but not for its zero character terminator. The space required for a null terminated string is given by strlen(string) + 1.

Upvotes: 1

AndreDurao
AndreDurao

Reputation: 5785

I thought that strlen was on string.h

NAME
     strlen, strnlen -- find length of string

LIBRARY
     Standard C Library (libc, -lc)

SYNOPSIS
     #include <string.h>

Upvotes: 1

merlin2011
merlin2011

Reputation: 75545

Try to avoid using strcpy. Instead,

strncpy(my_kitty, a, a_length + 1);

Upvotes: 1

Related Questions