2

I have a simple doubt in char arrays. I have a structure:

struct abc {
char *charptr;
int a;
}

void func1()
{
    func2("hello");
}

void func (char *name)
{
    strcpy(abc.charptr, name); // This is wrong. 
}

This strcpy will result in a crash since I do not have any memory allocated to the charptr. The question is : For mallocing this memory, can we do

abc.charptr = (char *) malloc(strlen(name)); //?
strcpy(abc.charptr, name); // Is this (or strncpy) right ?

Is this right ?

Vishnu CS
  • 748
  • 1
  • 10
  • 24
Vin
  • 717
  • 1
  • 12
  • 26
  • You need to allocate `strlen(name)+1` because `strlen` does not count the `\0` byte that terminates a C-style string. – wkl Oct 11 '11 at 18:47

3 Answers3

7

If you were to use malloc() you need to remember to make room for the null-terminator. So use malloc(strlen(name)+1) before calling strcpy().

But in this case you should just use strdup() which does the allocation and copying in one go:

abc.charptr = strdup(name);

The memory returned by strdup() has been allocated with malloc() and hence must be disposed of with a call to free().

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
6

It needs to be:

abc.charptr = malloc(strlen(name)+1); ?
strcpy(abc.charptr, name);

The return value of strlen doesn't include space for the null zero '\0' at the end of the string.

You will also have to free your allocated memory at some point.

shf301
  • 31,086
  • 2
  • 52
  • 86
  • 2
    Generally speaking, don't cast the result of `malloc`. See http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc. –  Oct 11 '11 at 18:50
1
abc.charptr = (char *) malloc(strlen(name) + 1);

Note the +1, since you need space for the null terminator. Then strcpy() will be fine.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
Dabbler
  • 9,733
  • 5
  • 41
  • 64
  • 1
    Generally speaking, don't cast the result of `malloc`. See http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc. –  Oct 11 '11 at 18:50