Miguel Morujão
Miguel Morujão

Reputation: 1161

Struct Problems in C

I have the following struct

typedef struct rotor {
    char characters[26];
    char* rotationPos;
    char* aPosition;
} rotor;

and I want to create 3 instances of it like this:

char cadeia3[26] = "BDFHJLCPRTXVZNYEIWGAKMUSQO";
char cadeia2[26] = "AJDKSIRUXBLHWTMCQGZNPYFVOE";
char cadeia1[26] = "EKMFLGDQVZNTOWYHXUSPAIBRCJ";

rotor* r1;
rotor* r2;
rotor* r3;
r1 = createRotor(cadeia1, 20);
r2 = createRotor(cadeia2, 20);
r3 = createRotor(cadeia3, 20);

The createRotor function automatically creates a rotor:

rotor* createRotor(char* cadeia, char* c) {
    int aux;
    rotor* r;
    for (aux = 0; aux < 26; aux++) {
        if (cadeia[aux] == NULL || strlen(cadeia) > 26) {
            return -1;
        } else
            r->characters[aux] = cadeia[aux];
    }
    r->characters[26] = '\0';
    r->rotationPos = c;
    r->aPosition = r->characters[0];
    return r;
}

This only works for the first rotor... Whenever I want to verify the content or use in a function any of the other ones the program is "terminated". To me the strange thing is working for one perfectly and not for the others.

What am I doing wrong?

Upvotes: 1

Views: 220

Answers (3)

paulsm4
paulsm4

Reputation: 121599

Three suggested changes:

1) If you're using a byte constant (like "20"), define the parameter as "char c", not "char *c":

rotor* createRotor(char* cadeia, char* c)

2) More important, if your string is 26 letters long ... then the character array must be (at least) 27 characters:

typedef struct rotor {
    char characters[27];
    char* rotationPos;
    char* aPosition;
} rotor;
...
char cadeia3[27] = "BDFHJLCPRTXVZNYEIWGAKMUSQO";

3) Most important, make sure you ALLOCATE each of your "rotor" structs somewhere.

Upvotes: 0

amit
amit

Reputation: 178411

Looks like undefined behavior to me.

You are not allocating (dynamically) the memory needed to rotor anywhere. Your createRotor() function just stores data in some random junk address (that is the value of r), and you try to access it. You never initialize r to an address allocated for your program.

Upvotes: 3

ouah
ouah

Reputation: 145829

 char cadeia3[26] = "BDFHJLCPRTXVZNYEIWGAKMUSQO";

the string literal is already 26 characters long, which means there is no room for the null terminator in the array. So this call:

 strlen(cadeia);

will invoke undefined behavior.

Use:

 char cadeia3[27] = "BDFHJLCPRTXVZNYEIWGAKMUSQO";

or

 char cadeia3[] = "BDFHJLCPRTXVZNYEIWGAKMUSQO";

Upvotes: 2

Related Questions