jondinham
jondinham

Reputation: 8499

C++ error message: invalid pointer

I have a function to append a string to another string:

char* strjoin(char* str1,const char* str2) {
  long len1 = strlen(str1);
  long len2 = strlen(str2);
  char* result = (char*)malloc(len1+len2+1);

  memcpy(result,str1,len1+1);
  memcpy(result+len1,str2,len2+1);

  free(str1); <--------- program crashes here with error: invalid pointer
  return result;
}

And the code which calls the function above is like this:

char* str = "John";
str = strjoin(str,"\x20");
str = strjoin(str,"Doe");

In the function strjoin above, I allocate memory for the new string, so I free the old str1. Why is the str1 invalid pointer?

Upvotes: 0

Views: 1825

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

In the first call of join you are passing a pointer to string literal, which is read-only, to free. You should not be calling free unless you have allocated the memory being freed.

You can fix this in the caller by using strdup:

char* str = strdup("John");
str = strjoin(str,"\x20");
str = strjoin(str,"Doe");

Upvotes: 5

Related Questions