ThomDall
ThomDall

Reputation: 11

segmentation fault during memcpy

I am trying to make a function which reverses the order of a portion of a string. I'm new to using pointers and for some reason I can access the location of the characters of my string to copy out a substring, but I can't put them back into the same location...

When I try to copy the reversed substring back into its original location I get

Program received signal SIGSEGV, Segmentation fault. 0x00007ffff7b5dc66 in ?? () from /lib/x86_64-linux-gnu/libc.so.6

Any help would be awesome!

Here's what I have so far:

void reverse(char* line, int start, int end){

      char str[end-start];

      memcpy ( str , line + start , end-start );

      reverseSubString ( str );

      memcpy ( line + start, str , end-start );

}

void reverseSubString(char* str){

    int i, j, len;
    char temp;

    i=j=len=temp=0;

    len=strlen(str);

    for (i=0, j=len-1; i<=j; i++, j--)
    {
        temp=str[i];
        str[i]=str[j];
        str[j]=temp;
    }
}

Upvotes: 0

Views: 2913

Answers (2)

user529758
user529758

Reputation:

reverseSubstring() expects a NUL-terminated C string, because it calls strlen() on the string passed in. However, you fail to NUL-terminate your string in the reverse function. Either do that, or even better, pass in a length argument:

void reverseSubString(char *str, size_t len)
{
    int i, j;
    char temp;

    for (i = 0, j = len - 1; i <= j; i++, j--) {
        temp = str[i];
        str[i] = str[j];
        str[j] = temp;
    }
}

void reverse(char *line, int start, int end)
{
    char str[end - start];
    memcpy(str, line + start, end - start);
    reverseSubString(str, end - start);
    memcpy (line + start, str, end - start);
}

Upvotes: 1

Daniel Fischer
Daniel Fischer

Reputation: 183978

  char str[end-start];

  memcpy ( str , line + start , end-start );

Unless the 0-terminator of the original string is included, you have a char array that is not 0-terminated. So

len=strlen(str);

computes who-knows-what if that doesn't already crash. Then

for (i=0, j=len-1; i<=j; i++, j--)
{
    temp=str[i];
    str[i]=str[j];
    str[j]=temp;
}

accesses outside the allocated memory.

Upvotes: 3

Related Questions