I am currently getting a segmentation fault (Segmentation fault: 11), when I call newUnitID().

No idea what I am doing wrong.

This is my header file where the function is:

#include <iostream>
#include <cstring>
#include <string>
#include <cstdlib>
#include <ctime>
#include <vector>
#ifndef UnitManager
#define UnitManager
using namespace std;

char randomIDChar(){
    static const char alphanum[] =
        "0123456789"
        "!@#$%^&*"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz";
    int stringLength = sizeof(alphanum) - 1;
    srand(time(0));
    for(int z=0; z < 21; z++)
    {
        return alphanum[rand() % stringLength];
    }
    return 1;
}

string newUnitID(){
    vector<char> v;
    for(int i=0; i < 50; i++){
        v[i] = randomIDChar();
    }
    string str(v.begin(),v.end());
    return str;
}

#endif
有帮助吗?

解决方案

vector's operator [] access existing elements; it doesn't create new elements. You start with an empty vector so

v[i] = randomIDChar();

access beyond the vector's end. You could change this to

v.push_back(randomIDChar());

Note that there is also a problem with randomIDChar. You should only seed the random number generator once, probably before calling either of the functions posted. Any given seed will generate a predictable stream of 'random' numbers; time(0) returns a number of seconds so every call you make within 1 second will have the same seed and so will generate the same number when you later call rand

其他提示

v[i] = randomIDChar();

causes an undefined behavior since it attempts to write a character behind the bounds of the array (vector's internal buffer, which hasn't been previously allocated).

Also note that you don't need a vector of characters to later construct a string, you can work directly with std::string object. And also note that the way you generate the position of character produces quite skewed results, this would yield better results:

char randomIDChar(){
    static const char alphanum[] =
        "0123456789"
        "!@#$%^&*"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz";
    static int len = 0;
    if (len == 0) {
        srand(time(0));
        len = sizeof(alphanum) - 1;
    }
    int pos = ((double)rand() / ((double)RAND_MAX + 1.0)) * len;
    return alphanum[pos];
}

std::string newUnitID(){
    const int LEN = 50;
    std::string str(LEN, ' ');
    for(int i = 0; i < LEN; i++) {
        str[i] = randomIDChar();
    }
    return str;
}

Worth to have a look at: What is the best way to generate random numbers in C++?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top