0

I have to create a very inexpensive algorithm (processor and memory) to remove the first char from a string (char array) in C.

I'm currently using:

char *newvalue = strdup(value+1);
free(value);
value = newvalue;

But I want to know if there is some less expensive way to do that. The string value is dynamically allocated.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
h0m3
  • 104
  • 9

3 Answers3

5

value+1 is a char* that represent the string with the first character removed. It is the less expensive way to obtain such a string..

You'll have to be careful when freeing memory though to make sure to free the original pointer and not the shifted one.

Olotiar
  • 3,225
  • 1
  • 18
  • 37
  • 2
    Only if both strings are meant to be immutable. – Blagovest Buyukliev Jan 09 '14 at 16:07
  • 2
    @BlagovestBuyukliev: The question shows the original string being freed, so it is no longer needed. Therefore, it is not necessary that the string at `value+1` be immutable; it may be modified as desired, and the effect of that on the original string is irrelevant because the original string will not be used again. – Eric Postpischil Jan 09 '14 at 16:12
  • @Olotiar: In that case, i need to free the char before value+1, value[0]. I don't know if in that case the memory keeps mapped in the system with the status of "used" but without pointer to it, or ,the operating system do the job of cleaning this memory space for me. Since i can't use free because will clean the entire space, not only the position 0. – h0m3 Jan 09 '14 at 16:34
3

Reuse the original array. May or may not be faster, depend on the relative speed of memory (de)allocation and copy.

int size = strlen(value);
if (size > 0) memmove(value, value+1, size);
timrau
  • 22,578
  • 4
  • 51
  • 64
1

Since heap calls will be quite expensive, the obvious optimization is to avoid them.

If you need to do this often, you could probably come up with some simple wrapper around the bare pointer that can express this.

Something like:

typedef struct {
  const char *chars;
  size_t offset;
} mystring;

Then you'd need to devise an API to convert a mystring * into a character pointer, by adding the offset:

const char * mystring_get(const mystring *ms)
{
  return ms->chars + ms->offset;
}

and of course a function to create a suffix where the 1st character is removed:

mystring mystring_tail(const mystring *ms)
{
  const mystring suffix = { ms->chars, ms->offset + 1};

  return suffix;
}

note that mystring_tail() returns the new string structure by value, to avoid heap allocations.

unwind
  • 391,730
  • 64
  • 469
  • 606