Jonathan.
Jonathan.

Reputation: 55544

Copying a substring to the start of the string in C

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);

Upvotes: 0

Views: 92

Answers (4)

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.

Upvotes: -1

nightshade
nightshade

Reputation: 638

int main()
{
    char a[] = "        hey";
    int i = 0;
    char *p = a;
    while(a[i++] == ' ');

    strcpy(p, p + i - 1);
    printf("%s\n", a);
}

Upvotes: 0

mvw
mvw

Reputation: 5105

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.

Upvotes: 1

Roberto Reale
Roberto Reale

Reputation: 4317

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.

Upvotes: 3

Related Questions