Thread: malloc of char arrays

  1. #1
    Registered User
    Join Date
    Feb 2005
    Posts
    8

    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
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    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
    Location
    The edge of the known universe
    Posts
    39,661
    > 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
    Location
    Oregon, USA
    Posts
    3,218
    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 Cprogramming.com
    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