zeroSpook
zeroSpook

Reputation: 54

Replacing a Null Character with other character in C

In this code:

  int main()
{
    char arr[5]="knot";
    char *ptr, *ptr1;
    int i;
    ptr = &arr[1];
    ptr1 = ptr + 3;
    *ptr1 = 101;
    for(i=0 ; i<4 ; i++)
        printf("%c", *ptr++);

    return 0;
}

The output happens to be note.

What I understand is the line, ptr = &arr[1]; points ptr to the second memory location of the original array and ptr1 = ptr + 3; points ptr1 to where the null character('\0') is stored in the original array. After that *ptr1 = 101; replaces the null character('\0') in the original array with e. After that I am printing from where ptr is pointing upto 4 characters.

What I've interpreted the code is something like this

enter image description here

What I don't understand is, though I am replacing the null character('\0') with some other character, why does

puts(arr);

or

for(i=0 ; i<10 ; i++)
   printf("%c", arr[i]);

still prints note, and not some garbage value after printing e. In the second for loop statement I tried printing the array beyond it's scope and it still prints note.

Could it be that the memory locations after e just contains whitespaces? And is it safe to print a string/ character array like this in the future?

PS: I am using gcc (tdm64-1) 5.1.0

Upvotes: 0

Views: 1096

Answers (2)

Jackson
Jackson

Reputation: 1223

It probably happened to be the case for your instance. I replicated your code the following way:

for(i=0 ; i<25 ; i++){
    printf("%c", *ptr++);
}

printf("\n--------\n");


for(i=0 ; i<25 ; i++){
    printf("%c", arr[i]);
}

printf("\n--------\n");

i=0;
while(arr[i] != '\0'){
    printf("%c",arr[i++]);
}
printf("|");

and got the following

output

Probably better to not print using the for method you used. It will give you inaccurate result and possibly result in security issues not to mention there is a good chance of miscounting.

I personally think its better to stick with puts or while(arr!='\0') or if using a for loop set the stop condition to sizeof(arr)/sizeof(char)

Upvotes: 0

Sourav Ghosh
Sourav Ghosh

Reputation: 134386

Could it be that the memory locations after e just contains whitespaces?

Not exactly, but the value 0, which acts as a null terminator. So, somehow the functions handling strings are showing seemingly proper behaviour. For the loop and accessing individual element case anyways, attempting to access memory location which is not allocated to the process (i.e., not a valid memory) is undefined behaviour.

And is it safe to print a string/ character array like this in the future?

ABSOLUTELY NOT. The result you got is out of undefined behavior, it's neither guaranteed nor reliable.

Upvotes: 3

Related Questions