I should have a segmentation fault here... but I have not

May 26, 2016 at 9:50pm
Hello.

Look at this copy constructor:

1
2
3
4
5
6
7
8
9
10
11
12
13
GString(const GString& copy)
{
	size = copy.size;
	mainString = new char[size];

	int i = 0;
	for (; i < size; i++)
	{
		mainString[i] = copy.mainString[i];
	}

	mainString[i] = '\0';
}


This is very bad.

H E L L O

size = 5

I create an array of 5 elements without taking into account the \0 null character

At the end of the for loop, i will be 5 just like the size of the array.

So i'm writing on a piece of memory I shouldn't have access to.


I've tried this code several times before this great mistake turned out.

Why had this been working for all this time?
Last edited on May 26, 2016 at 9:51pm
May 26, 2016 at 10:15pm
The behavior of that code is undefined. Undefined behavior is not "the program will crash". Undefined behavior is "the standard permits a program with undefined behavior to cause demons to fly out your nose". Anything can happen, including nothing.
May 26, 2016 at 10:15pm
A segFault will occur when you try to read or write memory that the operating system didn't set aside for your process.

Your array is one little piece of that memory. Writing a single byte over the end of your array will only be a problem if your array happens to be right at the end of that memory.
May 26, 2016 at 10:27pm
> Writing a single byte over the end of your array will only be a problem
It is always a problem.
Topic archived. No new replies allowed.