Thread: malloc of char arrays

  1. #1
    Registered User
    Join Date
    Feb 2005

    Question malloc of char arrays

    A friend tells me that in C when u malloc a char array u have to allocate length of the string + 2 (1 for the '\0' and 1 cause C needs it for some reason, i forget why tho). Just windering if this is right? and if i just statically allocate the array in the variables declaration that i only need to allocate for the size of the string.

    Thanx for any help you can give.

  2. #2
    Super Moderator
    Join Date
    Sep 2001
    For chars, you're simply specifying the number of bytes/chars to be allocated. That means the number of characters, plus one for the null character.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    > Just windering if this is right?
    Nope, it's just strlen(string) + 1 if you want to allocate memory for string
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Gawking at stupidity
    Join Date
    Jul 2004
    Oregon, USA
    What Salem said.
    If you understand what you're doing, you're not learning anything.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A Full Program to analyze.
    By sergioms in forum C Programming
    Replies: 2
    Last Post: 12-30-2008, 09:42 AM
  2. The Interactive Animation - my first released C program
    By ulillillia in forum A Brief History of
    Replies: 48
    Last Post: 05-10-2007, 02:25 AM
  3. lvalue error trying to copy between structures
    By emanresu in forum C Programming
    Replies: 2
    Last Post: 11-16-2006, 06:53 AM
  4. Replies: 16
    Last Post: 10-29-2006, 05:04 AM
  5. Need help understanding info in a header file
    By hicpics in forum C Programming
    Replies: 8
    Last Post: 12-02-2005, 12:36 PM