fitting a string in an array of pointer to characters

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] << " ";
}

return 0;

}
Sorry to be so blunt, but that is totally wrong.

new char allocates space for 1 byte. 1 "character" fits in 1 byte.

And that is exactly what I thought. But I can fit in full 7 character word in the array[count], by doing -

array[count] = new char;
strcpy(array[count], token);

I'm running it in MS VC++ 6.0
No, you can't. You're merely producing a non-fatal segmentation fault.
Then why is it crashing at more than 7 characters and not at 7? Really strange!

I may have found out why it was acting that way.

array[count] = new char;
cout << endl << sizeof(array[count]) << endl;

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.
Topic archived. No new replies allowed.