Below program tokenizes string in s1 and stores each token in array of pointers array[count].
The statement:
array[count] = new char;
allocates 4 bytes to pointer in array[count]. And I know that size of a character is 1 byte. That should mean that a total of only 4 bytes should be able to fit in memory pointed by array[count]. I saw that I can fit upto 7 characters. This is obeying the rule of 2 characters per byte. I am confused. Can someone clarify please?
int strtok()
{
char s1[]="worlddd";
char *token;
char *array[10];
int count = 0;
token=strtok(s1, " -,.");
if(token)
{
array[count] = new char;
cout << endl << sizeof(array[count]) << endl;
strcpy(array[count],token);
}
while (token!=NULL)
{
cout << token << endl;
token=strtok(NULL, " -,.");
if (token)
{
count++;
array[count] = new char;
strcpy(array[count],token);
}
}
for (int x=count; x >=0; x--)
{
cout << array[x] << " ";
}
the sizeof(array[count]) above is actually adding the size of pointer (which is 4 bytes) with the size of char and thats why it is giving 4+(whatever lenth string I copy to array[count]). Is it because its a double pointer?
No. It's not strange at all. Not all buffer overflows instantly crash the program. The exact amount of overflow required for that depends on the system. Windows, for example, tends to be more forgiving around overflows than Linux.
You're merely producing a non-fatal segmentation fault.
Just because it doesn't crash doesn't mean it's not wrong.