When using the strcat() function, an error occurs (at any time, if you call the function more than once):

 char *g = strcat(strdup(f),strdup(f)); 

The error is this:

 03-31 14:59:24.163 29228-29228/optichat.testotest A/libc: invalid address or address of corrupt block 0xb8facbe0 passed to dlfree 03-31 14:59:24.164 29228-29228/optichat.testotest A/libc: Fatal signal 11 (SIGSEGV), code 1, fault addr 0xdeadbaad in tid 29228 (ichat.testotest) 

How to solve this problem?

  • There is nothing specific for c ++ 11 , and for c ++ too. The strdup function strdup generic and not even standard. - 伪位蔚蠂慰位蠀蟿

1 answer 1

The character array returned by the strdup(f) function does not have enough space to include itself.

 char *g = strcat(strdup(f),strdup(f)); 

The array used as the first argument of the function must have enough space so that you can add a string to it. For a reduced call, its size must be at least 2 * strlen( f ) + 1 .

In addition, there is a memory leak, because the address of the dynamically created array for the second argument is lost, and the created array cannot be deleted.

You cannot create new lines on the fly.

If this is a C ++ program, then the standard class std::string should be used. Then you can just write

 std::string s( f ); s += f; 

Or as a temporary expression

 std::string( f ) + f 

If this is a C program, the sample code might look like this.

 char *s = malloc( 2 * strlen( f ) + 1 ); strcat( strcpy( s, f ), f ); //... free( s ); 

The same thing in C ++ will look like

 char *s = new char[2 * strlen( f ) + 1]; strcat( strcpy( s, f ), f ); //... delete [] s; 
  • Thank you, is this option on the pros right? char result [2 * strlen (f) +1]; strcpy (result, f); strcat (result, f); - Flappy
  • @Flappy Actually, C ++ does not support variable-length arrays. Either you need to use the class std :: string, or dynamically allocate memory as char * res = new char [2 * strlen (f) + 1]; strcat (strcpy (res, f), f); - Vlad from Moscow
  • @Flappy on pluses should use std::string . strcat / strcpy is a great way! - 伪位蔚蠂慰位蠀蟿
  • Thank you all for the advice, generally green in it) - Flappy