Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Segmentation fault (core dumped) when accessing memory that has been allocated via new()

When trying to check for a value that has been initialized via new(), I can a segmentation fault error.

int main() {
  const char* const *matrix = new(char*);
  std::cout << matrix[0][0]; // segfault here
  return 0;
}

My suggestion is that there should be garbage value, but no segfault.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You allocate new(char*) and assign in to matrix, which makes matrix[0] to not be a segfault because matrix is a valid pointer.

However, matrix[0] is not a valid pointer. It contains a garbage data, so matrix[0][0] tries to get a random memory location, which ends in a segfault.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading