odd behavior with Character Arrays

Bob Plantz plantz@cds1.net
Fri Aug 8 15:38:00 GMT 2008


> If i give the size of the array as 15, like "unsigned char n[15] =
> {'a', 'b', 'c','d'};" , then it is appending '\0'.
> But if the size of the array is not given "unsigned char n[] ", then
> it is not appending '\0'.
> 
> Does that mean, that if the size of the array is specified, it appends
> '\0' and if it is not specified then it does not append '\0'?
> Can you/anyone clarify this point?

I does more than just append a '\0'. It first zeroes the entire array,
then stores your characters there, one at a time.

Here is the (64-bit) assembly language for the beginning of your main
function. I have annotated it to show what's happening to the array.
main:
.LFB3:
	pushq	%rbp                     # save caller's base pointer
.LCFI2:
	movq	%rsp, %rbp         # establish our base pointer
.LCFI3:
	subq	$48, %rsp           # get memory for local variables
.LCFI4:
	movq	%fs:40, %rax      # these three instructions are used to
	movq	%rax, -8(%rbp) # check for stack boundary violation
	xorl	%eax, %eax
# The array is in the stack frame, starting -32 from the base pointer
	movq	$0, -32(%rbp)    # zero first 8 bytes of array
	movl	$0, -24(%rbp)    # zero next 4 bytes of array
	movw	$0, -20(%rbp)    # zero next 2 bytes of array
	movb	$0, -18(%rbp)    # zero next byte of array
# Now all 15 bytes of the array have been zeroed.
	movb	$97, -32(%rbp)   # n[0] = 'a';
	movb	$98, -31(%rbp)   # n[1] = 'b';
	movb	$99, -30(%rbp)   # n[2] = 'c';
	movb	$100, -29(%rbp) # n[3] = 'd';
	leaq	-32(%rbp), %rdi # load address of array
	call	slen
	movl	%eax, -36(%rbp) # t = slen(n);
	leaq	-32(%rbp), %rdi # load address of array
	call	slen
	movl	%eax, g(%rip)      # g = slen(n);
	movl	g(%rip), %edx       # load g
	movl	-36(%rbp), %esi   # load t
	movl	$.LC0, %edi           # address of "\n t = %d, g = %d\n"
	movl	$0, %eax                 # no SSE arguments
	call	printf
	movl	$0, %eax                  # return 0;
	movq	-8(%rbp), %rdx      # these three instructions
	xorq	%fs:40, %rdx          # check for stack boundary
	je	.L8
	call	__stack_chk_fail # violation
.L8:
	leave                                        # undo stack set up
	ret                                            # return to caller

Bob




More information about the Gcc-help mailing list