2

I've got a string declared like this:

str=malloc(sizeof(char)*128);

I want to clear it completely so that whenI do strncat() operation, the new characters will be written to the beginning of str. The reason I need to clear it is that I'm writing over it with a simplified version of itself (deleting excess whitespace).

Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
nick_name
  • 1,353
  • 3
  • 24
  • 39

3 Answers3

13

I suggest you simply do this:

*str = '\0';

You don't need to clear the entire contents of the buffer. You can just set the first char to zero and then you have the empty string.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • You beat me to this answer... He doesn't need to set the **entire** array to 0, so this is much faster. +1 – lnafziger Apr 17 '12 at 15:09
4

Use memset:

memset(str, 0, sizeof(char)*128);

Regardless of this, if you are writing the string over itself, you shouldn't use strcat - the objects that you copy must not overlap:

If copying takes place between objects that overlap, the behavior is undefined.

and a string definitely overlaps with itself.

Removing whitespace from a string can be easily achieved with a simple function:

void remove_space(char* r) {
    char *w = r;
    do { *w = *r++; w += *w && !isspace(*w); } while (*w);
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • how do I call `remove_space` function? I tried `char * a = "kk a"; remove_space(a); printf("[%s]\n", a);` but it returns `Segment fault`. – Jack Apr 17 '12 at 18:07
  • 1
    @Jack You need to make the string writable: `char a[] = "kk a"; remove_space(a); printf("[%s]\n", a);` – Sergey Kalinichenko Apr 17 '12 at 18:41
3

You would like to use calloc instead of plain malloc?

Something like

calloc(128, sizeof(char));

EDIT Also, strncat doesn't require you having a null terminated string at the destination. Just make sure that the destination is large enough to hold the concatenated resulting string, including the additional null-character.

And as dasblinkenlight notes, do not copy overlappingly with strncat. Consider using normal dst[i++] = src[j++] way of copying.

Community
  • 1
  • 1
Pavan Manjunath
  • 27,404
  • 12
  • 99
  • 125