Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a string pointer in C be directly assigned a string literal?

The following program works fine, and I'm surprised why :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

void xyz(char **value)
{
        // *value = strdup("abc");
        *value = "abc"; // <-- ??????????
}

int main(void)
{
        char *s1;

        xyz(&s1);

        printf("s1 : %s \n", s1);
}

Output :

s1 : abc

My understanding was that I have to use strdup() function to allocate memory for a string in C for which I have not allocated memory. But in this case the program seems to be working fine by just assigning string value using " ", can anyone please explain ?

like image 638
androidFan Avatar asked Dec 19 '22 09:12

androidFan


1 Answers

String literals don't exist in the ether. They reside in your programs memory and have an address.

Consequently you can assign that address to pointers. The behavior of your program is well defined, and nothing bad will happen, so long as you don't attempt to modify a literal through a pointer.

For that reason, it's best to make the compiler work for you by being const correct. Prefer to mark the pointee type as const whenever possible, and your compiler will object to modification attempts.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

void xyz(char const **value)
{
        *value = "abc";
}

int main(void)
{
        char const *s1;

        xyz(&s1);

        printf("s1 : %s \n", s1);
        s1[0] = 'a'; << Error on this line
}
like image 135
StoryTeller - Unslander Monica Avatar answered May 01 '23 15:05

StoryTeller - Unslander Monica