2

I have following code and the out put:-

#include<stdio.h>
int main()
{
char pal_tmp[4];
printf("Size of String Variable %d\n",sizeof(pal_tmp));
strcpy(pal_tmp,"123456789");
printf("Printing Extended Ascii: %s\n",pal_tmp);
printf("Size of String Variable %d\n",sizeof(pal_tmp));
}

Out put:-

Size of String Variable 4
Printing Extended Ascii: 123456789
Size of String Variable 4

My questions is Why String variable (character array) accepts characters more than what its capacity is? Should not it just print 1234 instead of 123456789 ?

Am I doing something wrong?

CodeCodeCode
  • 459
  • 1
  • 12
  • 21

6 Answers6

9

Well yes. You are doing something wrong. You're putting more characters into the string than you are supposed to. According to the C specification, that is wrong and referred to as "undefined behaviour".

However, that very same C specification does not require the compiler (nor runtime) to actually flag that as an error. "Undefined behaviour" means that anything could happen, including getting an error, random data corruption or the program actually working.

In this particular case, your call to strcpy simply writes outside the reserved memory and will overwrite whatever happens to be stored after the array. There is probably nothing of importance there, which is why nothing bad seems to happen.

As an example of what would happen if you do have something relevant after the array, let's add a variable to see what happens to it:

#include <stdio.h>

int main( void )
{
    char foo[4];
    int bar = 0;

    strcpy( foo, "a long string here" );
    printf( "%d\n", bar );

    return 0;
}

When run, I get the result 1701322855 on my machine (the results on yours will likely be different).

The call to strcpy clobbered the content of the bar variable, resulting in the random output that you saw.

Elias Mårtenson
  • 3,820
  • 23
  • 32
2

Well yes, you are overwriting memory that doesn't belong to that buffer (pal_tmp). In some cases this might work, in others you might get a segfault and your program will crash. In the case you showed, it looks like you happened to not overwrite anything "useful". If you tried to write more, you'll be more likely to overwrite something useful and crash the program.

Oleksi
  • 12,947
  • 4
  • 56
  • 80
1

C arrays of char don't have a predefined size, as far as the string handling functions are concerned. The functions will happily write off the end of the array into other variables (bad), or malloc's bookkeeping data (worse), or the call stack's bookkeeping data (even worse). The C standard makes this undefined behaviour, and for good reason.

If a version of a particular function accepts a size argument to limit how much data it writes, use it. It protects you against this stuff.

0

C does not keep track of the size of strings (or arrays, or allocated memory, etc.), so that is your job. If you create a string, you must be careful to always make sure it never gets longer than the amount of memory you've allocated to it.

Gabe
  • 84,912
  • 12
  • 139
  • 238
  • C does keep track of the sizes of arrays, but it doesn't make it easy for C programmers to keep track of it. For example, passing an array name as a function argument passes a pointer to the first element of the array. The size of the array is still implicitly tracked, like the size of any object, but that information is not passed to the function unless you do it yourself. – Keith Thompson May 23 '13 at 15:07
0

In C language Strings are defined as an array of characters or a pointer to a portion of memory containing ASCII characters. A string in C is a sequence of zero or more characters followed by a NULL '\0' character. It is important to preserve the NULL terminating character as it is how C defines and manages variable length strings. All the C standard library functions require this for successful operation.

For complete reference refer this

Dharmesh Patel
  • 1,881
  • 1
  • 11
  • 12
  • A string is by definition "a contiguous sequence of characters terminated by and including the first null character" (that's a direct quote from the C standard). A pointer is not a string. Characters in a string are not necessarily ASCII. The `'\0'` terminator is a null character, not a NULL character; `NULL` is a macro that expands to a null *pointer* constant. The reference you linked to says it's obsolete. The [updated reference](http://www.tutorialspoint.com/cprogramming/c_strings.htm) is actually fairly decent; the only error I found is the use of `"%d"` to print a `size_t` value. – Keith Thompson May 23 '13 at 15:04
0

Function strcpy doesn't have knowledge about the length of the character array - this function is considered as unsecure.

You may use strncpy, where you tell the size of the buffer and if longer argument is provided, only the memory of the buffer is used and nothing else is changed.

V-X
  • 2,979
  • 18
  • 28
  • No, don't use `strncpy`. It is an obsolete, unsafe function. [More info here](http://stackoverflow.com/questions/2114896/why-is-strlcpy-and-strlcat-considered-to-be-insecure). Use `memcpy` and manual null termination instead (which also executes faster than `strncpy`). – Lundin May 23 '13 at 06:12
  • Or just use `strcpy`, but *only* after verifying that the target array is big enough. – Keith Thompson May 23 '13 at 06:52
  • [My rant on `strncpy`](http://the-flat-trantor-society.blogspot.com/2012/03/no-strncpy-is-not-safer-strcpy.html). – Keith Thompson May 23 '13 at 14:58