Search code examples
c++nvcc

Segmentation fault: 11 - C function


I have "segmentation fault:11" with this code, and I can't find a solution

static const int N = 512;
static const int M = 64;
static const int K = sizeof(int) * 8;
static const int SZ = N*M / K;

void readFromFile(int *v);

int main(void){
    int v[SZ];
    readFromFile(v);
 }

void readFromFile(int *v) {
    ifstream f;
    f.open("...path/file.txt");
    char c = f.get();
    int i = 0;
    while (f.good()) {
       v[i] = c - '0';
       c = f.get();
       i++;
   }
   f.close();
}

I have an int array and a file used to fill the array. It's a piece of code used to fill int array for cuda computing. I'm using nsight and nvcc.


Solution

  • You code says N = 512 and you declare v as int v[N]; But if your file has more character than N then i get bigger than N and segmentation fault generate as you access invalid index of v.

    int i = 0;
    while (f.good()) {
       v[i] = c - '0';
       c = f.get();
       i++;                    //No checking if it is greater than N
    }
    

    Actually it's better to use like

    char c;
    int i = 0;
    while ((c=f.get())!=EOF) {
       v[i] = c - '0';
       i++;
    }
    

    And you should also check limit of i for further error minimization.