-1

I create two files described below

csvreport.h

int flag = 0; //declared && defined

table.cpp

csvreport* csvreports;
csvreports->flag = 1;

it is showing segmentation fault (code dumped)
any one can give solution for it??

3 Answers3

5

csvreport* csvreports; creates uninitialized pointer. Attempt to use uninitialized pointer results in undefined behavior.

Either create this variable on stack, without pointer:

csvreport csvreports;

or, in case if pointer needed - allocate it first:

csvreport* csvreports = new csvreport;
csvreports->flag = 1;

or use unique pointer via modern C++11 way:

auto csvreports = std::make_unique<csvreport>();
csvreports->flag = 1;
Starl1ght
  • 4,422
  • 1
  • 21
  • 49
1

You are trying to access the member of an object using a pointer that has been declared but not initialized to point to anything valid. That is cause for undefined behavior.

Allocate memory for the object first before attempting to access members of the type.

csvreport* csvreports = new csvreport; // or new csvreport[array_size]
csvreports->flag = 1;
R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

In this code

csvreport* csvreports;
csvreports->flag = 1;

cvsreports is just declared as a pointer; no memory is allocated for it to point to.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
Mohan Kumar P
  • 3,122
  • 1
  • 14
  • 17