0

statements like: char *a = "hello" or char *b[]= {"yes", "no"} seem to be accessible and printable without any problems in C. Do they require a malloc?

effeffe
  • 2,821
  • 3
  • 21
  • 44
Alon T
  • 27
  • 5
  • 3
    No they do not. The C and C++ standards both explicitly allow string literals to be used to initialise pointers to `char` (the result being a pointer to the first character in the literal). Note it is better to prefix with `const` - since changing a string literal using such a pointer gives undefined behaviour. – Peter May 12 '18 at 09:19
  • @Peter, C++ does not unless you have the `const`, as of C++11. – chris May 12 '18 at 09:32

2 Answers2

3

Case 1 :- char *a = "hello"; Here a is char pointer and it needs valid address and its assigned with valid address as hello is string i.e address. So no need of malloc() here.

Case 2 :- char *b[]= {"yes", "no"}; Here b is array of char pointer i.e each element of b is pointer that means each elements needs to be initialized with valid address and its assigned with valid address as b[0] with yes(i.e address) and b[1] with no(i.e address). So here also no need of malloc().

Achal
  • 11,821
  • 2
  • 15
  • 37
  • Case 3: This is unsafe as scanf() will not do boundary checking and may well copy beyond the end of the allocated memory, leading to a segmentation fault or worse (e.g. buffer overflow attack). Giving examples of this kind of practice in an answer may lead to insecure code so I think it should be pointed out even if only used for pedagogic effect. – ThomasH May 12 '18 at 09:53
  • yes @ThomasH I explained case-3 with both scenerio. In first its uninitialized if OP scan the input, it cause seg. fault & in second case I suggest to allocate memory using `malloc()`. Read here about `scanf()` about unsafe https://stackoverflow.com/questions/2430303/disadvantages-of-scanf#answer-2430978 – Achal May 12 '18 at 09:55
0

"hello" here is string constant which is residing in data segment which is readable section of memory.

char *a ="hello" is nothing but you are assigning the address of const string "hello" to char pointer a.

if you try to modify content of this const string using ptr a it will crash. e.g a[1]= 'E' /// -> this is undefined behavior

If you want to own memory then malloc and copy string into memory created using malloc.

  • 2
    Attempting to modify a string literal invokes *undefined behavior* - there is no guarantee that it will "crash". Also `char[] = "hello";` creates a modifiable copy, there is no need for `malloc` – UnholySheep May 12 '18 at 09:23
  • i agree .. edited thanks – Siddesh Parmar May 12 '18 at 09:24
  • "if you try to modify content of this const string using ptr a it will crash." not really, it's undefined behavior and anything can happen. Modern implementations on PCs will crash, on other implementations it may happily comply, and now all the instances of that literal are modified. – Matteo Italia May 12 '18 at 09:25