0

This program keep crashing after printing first 'ok'. I am running it on VS Code using g++ compiler.

#include<stdio.h>
#include<stdlib.h>

struct rod {
    char name;
    int *list;
    int index;
};

int main()
{
    int n=3;
    struct rod *rodA, *rodB, *rodC;
    rodA->name = 'A';
    printf("ok");
    rodB->name = 'B';
    printf("ok");
    rodC->name = 'C';
    printf("ok");
    rodA->list = (int*) calloc(n, sizeof(int));
    rodB->list = (int*) calloc(n, sizeof(int));
    rodC->list = (int*) calloc(n, sizeof(int));
}
puneetred
  • 39
  • 3
  • 5
    You are using uninitialized pointers. – Fred Larson May 09 '22 at 17:22
  • 3
    Please see https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior. It is only accidental that the first "ok" prints; all of the code is wrong. Hint: when you write `struct rod *rodA, *rodB, *rodC;`, what do you think this means, exactly? What is the purpose of a pointer - to *point at* something, right? What happens if you do not say where it should point? Does this code say where the pointers should point? How? – Karl Knechtel May 09 '22 at 17:23
  • You should wonder why it even printed it once. Doesn't your compiler warn you about using uninitialized variables? If not, you should add optione `-Wall -Wextra -pedantic`. – Gerhardh May 09 '22 at 17:23

2 Answers2

1

This line declares three pointer variables, but never initializes them.

struct rod *rodA, *rodB, *rodC;

Then this line corrupts memory because you never set the pointers to a valid memory address:

rodA->name = 'A';

After that, the behavior of the program is 'undefined' and eventually will crash.

Chuck Walbourn
  • 38,259
  • 2
  • 58
  • 81
0

That is because of memory violation. You create pointers that point to nothing (garbage). One of them seems to point to read-only memory, and when you try to assign something to it, program crashes. Try allocating them like this:

struct rod *rodA = calloc(1, sizeof(struct rod));
Jakub Bednarski
  • 261
  • 3
  • 9