Search code examples
c++arrayssegmentation-faultcurly-bracesstrcpy

C++ Seg Fault at end of function. Reference line = closing brace


In conclusion: Thanks so much everyone! All the responses posted below were correct. The initial error was me forgetting to leave room for the NULL terminator. Strcpy() is a dangerous function because when I used it, it didn't know when the end of the 'string' was. Therefore, strcpy() grabbed to much data and overwrote the return address.

EDIT: added more code from the program

SOLVED: Honestly, my initial implementation was crap. I don't even know why I wrote swap that way if I wanted to swap out elements of the array. (At the time, each element only had the a char array in it. So I was able to get away with the old implementation). I have re-written it to:

void swap(ArrayElement list[], int index1, int index2) {
     ArrayElement temp;
     temp = list[index1];
     list[index1] = list[index2];
     list[index2] = temp;
}

I'm having problems with a segmentation fault at the end of the following function.

struct ArrayElement {
    char data[SIZE_OF_ELEMENT];
    // Implemented this way so that I can expand to multiple values later on
}

//In main:
ArrayElement* list = new ArrayElement[NUM_OF_ELEMENTS];

void swap(ArrayElement list[], int index1, int index2) {
     char temp[SIZE_OF_ELEMENT];
     strcpy(temp, list[index2].data);
     strcpy(list[index2].data, list[index1].data);
     strcpy(list[index1].data, temp);
}

The error is a segmentation fault at line 45, which is the ending curly brace of the function. This was compiled using g++. I used gbd to try and debug it and everything works correctly until it hits the curly brace.

I can give more code from the program if it is needed. I don't want to post the entire thing because this is for a class.


Solution

  • My best guess is, the string at list[index2].data is larger than temp[] and by copying, you overwrote the stack and the return address.

    Try inserting a test for the length:

    #include <iostream>
    
    ...
    int n = strlen(list[index2].data);
    std::cerr << "len=" << n << ", SIZE_OF_ELEMENT=" << SIZE_OF_ELEMENT << std::endl;
    

    and see, if n (list[index2].data) is larger than SIZE_OF_ELEMENT