0

I am trying to remove the whitespace at the start of a string, I have the index of the first non whitespace character, so I tried to do this:

int firstNonWhitespace = ...;
char *line = ...;
char *realStart = line + firstNonWhiteSpace;
strcpy(line, realStart);

but got Abort Trap 6 when at runtime.

However it works if I copy the realStart string to a temporary string, and then copy the temporary string to line:

int firstNonWhitespace = ...;
char *line = ...;
char *realStart = line + firstNonWhiteSpace;
char *tstring = malloc(strlen(realStart) + 1);
strcpy(tstring, realStart);
strncpy(line, tstring, strlen(line));
free(tstring);
Jonathan.
  • 53,997
  • 54
  • 186
  • 290
  • For all practical purposes, can't you just use the realStart to refer to the string from there onwards? – asb Jun 12 '14 at 15:25
  • 1
    ["If copying takes place between objects that overlap, the behavior is undefined."](http://pubs.opengroup.org/onlinepubs/9699919799/functions/strcpy.html). – pmg Jun 12 '14 at 15:26
  • Please spell out "char *line = ...;" What did you replace with ...? – jarmod Jun 12 '14 at 15:27
  • `strcpy` doesn't like overlapping strings. See http://stackoverflow.com/questions/7427596/how-to-fix-strcpy-so-that-it-detects-overlapping-strings for several alternatives. – Jongware Jun 12 '14 at 15:27

4 Answers4

3

There are two problems with your code.

  1. The source and destination in the call to strcpy() do overlap, which results in Undefined Behaviour.

  2. It might well be the case that realStart points to some non-writeable area of memory.

Roberto Reale
  • 4,247
  • 1
  • 17
  • 21
1

The faster way is

line += firstNonWhiteSpace;

but that might have consequences for your memory management, in case that part of memory was dynamically allocated. Only do this if you know what you are doing.

mvw
  • 5,075
  • 1
  • 28
  • 34
  • But that will not affect the string after the function returns. And the function is not passed a pointer to a string – Jonathan. Jun 12 '14 at 19:06
  • What function? I have no crystal ball, only those few lines you posted and they say not much about your environment. – mvw Jun 12 '14 at 19:14
0
int main()
{
    char a[] = "        hey";
    int i = 0;
    char *p = a;
    while(a[i++] == ' ');

    strcpy(p, p + i - 1);
    printf("%s\n", a);
}
nightshade
  • 638
  • 5
  • 15
-1

Your problem is likely that you are not allowed to modify string literals, i. e. the code

int main() {
    int firstNonWhitespace = 3;
    char *line = "   foo";
    char *realStart = line + firstNonWhiteSpace;
    strcpy(line, realStart);
}

may or may not work depending on whether your platform protects against modifying the string literal " foo". Copying the string first is required by the language standard.

Also, since strcpy() is not guaranteed to work correctly on overlapping strings (you might get lucky, though), use memmove() to do the moving.

cmaster - reinstate monica
  • 38,891
  • 9
  • 62
  • 106