Thread: Trouble solving Invalid write of size 1 please advice

  1. #1
    Registered User
    Join Date
    Nov 2010
    Posts
    3

    [SOLVED] Trouble solving Invalid write of size 1 please advice

    I wrote a reverse function it works fine but having trouble solving valgrind throwing
    Code:
    #include <string.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    char *strrev(char *str){
      char *tmp = malloc(sizeof(char) * strlen(str));
      memset(tmp,0,strlen(str));
      for(int i=0, k=(int)strlen(str); i<=(int)strlen(str); i++, k--){
        printf("%c\n", str[k]);
        strncat(tmp, &str[k], 1);
      }
      return tmp;
    }
    int main(){
        char *str = strrev("ABCD");
        printf("%s\n", str);
        free(str);
        return 0;
    }
    Please advice
    Last edited by Mr.President; 08-22-2020 at 02:41 AM.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Eh. You need to account for the terminating null character. You only need to call strlen(str) once: store the result in a size_t variable. Your loop index variables should be size_t too. Finally, strncat is overkill and inefficient: just assign characters.

    Another approach could be to implement an in-place string reverse, then call that in-place string reverse to implement this string copy and reverse.

    By the way, I suggest you rename your strrev function: if I remember correctly, it is technically a reserved name (something to with the str prefix, I think, rather than there being such a standard function), and more practically it could conflict with a strrev provided as a standard library extension.
    Last edited by laserlight; 08-22-2020 at 02:24 AM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Nov 2010
    Posts
    3
    yes thank you ! darn I missed the terminating 0/
    Code:
    #include <string.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    char *strrev(char *str){
      size_t len = strlen(str);
      char *tmp = malloc(sizeof(char) * len + 1);
      memset(tmp, 0, len);
      for(size_t i=0, k=len-1; i<len; i++, k--){
          tmp[i] = str[k];
      }
      tmp[len] = 0;
      return tmp;
    }
    int main(){
        char *str = strrev("ABCD");
        printf("%s\n", str);
        free(str);
        return 0;
    }
    All works fine now !

  4. #4
    Registered User
    Join Date
    Feb 2019
    Posts
    1,078
    Not that your strrev() is wrong, but I prefer to follow C's standard library philosophy and assume the arguments are correct and test/initialize them outside the funcion. I would implement strrev() this way:

    Code:
    // Notice: No malloc() and just one call to strlen().
    char *strrev2( char *destp, const char *srcp )
    {
      const char *p;
      char *q;
    
      // Points to source string NUL char.
      p = srcp + strlen( srcp );
    
      // Initially the destination string is empty.
      *destp = 0;
    
      // if source string isn't empty...
      if ( *p-- )
      {
        // Copy bytes in reverse order.
        q = destp;
        while ( p >= srcp )
          *q++ = *p--;
    
        // puts the final NUL char at destination string.
        *q = 0;
      }    
    
      // Returns destination string pointer.
      return destp;
    }
    If you pass invalid pointers you'll get a 'segmentation fault' or misbehavior the same way it happens to strlen() (passing a NULL pointer to srcp, for example).

    And you'll need to allocate the destination string before calling the function, the same way it happens with strcpy(), for example.

  5. #5
    Registered User Sir Galahad's Avatar
    Join Date
    Nov 2016
    Location
    The Round Table
    Posts
    277
    Reverse in-place using swaps:

    Code:
    #include <string.h>
    
    char* reverse(char* text)
    {
     char* left = text;
     char* right = text + strlen(text);
     while(left < --right)
     {
      char saved = *left;
      *left++ = *right;
      *right = saved;
     } 
     return text;
    }
    
    char* reversed(char* destination, const char* source, size_t max)
    {
     strncpy(destination, source, max);
     return reverse(destination);
    }
    
    #include <stdio.h>
    
    int main(void)
    {
     char buffer[1024];
     for(;;)
     {
      printf("Input to reverse (press `enter` to exit) > ");
      fgets(buffer, sizeof(buffer), stdin);
      char* newline = strstr(buffer, "\n");
      if(newline)
       *newline = 0;
      if(*buffer == 0)
       break;
      puts(reverse(buffer)); 
     }
    }
    Note that the null-termination step isn't necessary here since it's only the enclosing chars are being swapped out.

  6. #6
    Registered User
    Join Date
    Feb 2019
    Posts
    1,078
    Quote Originally Posted by Sir Galahad View Post
    Reverse in-place using swaps
    Nice!

  7. #7
    Registered User Sir Galahad's Avatar
    Join Date
    Nov 2016
    Location
    The Round Table
    Posts
    277
    Thanks. And kudos to you for a better job of code documentation. I do try to make mine as self-documenting as possible, but in the process oft times forget to do much commenting...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Client switching stack / invalid write/read size valgrind
    By thunderz1337 in forum C Programming
    Replies: 3
    Last Post: 10-05-2019, 07:36 AM
  2. free(): invalid next size (fast)
    By livin in forum C Programming
    Replies: 13
    Last Post: 08-01-2012, 01:56 AM
  3. realloc(): invalid size:
    By fxtdr79 in forum C Programming
    Replies: 4
    Last Post: 06-03-2010, 09:30 PM
  4. having trouble solving a program
    By everyone0 in forum C Programming
    Replies: 10
    Last Post: 05-27-2010, 03:10 PM
  5. Having trouble solving maze.
    By eurus in forum C Programming
    Replies: 3
    Last Post: 02-17-2006, 01:52 AM

Tags for this Thread