Does make char * point to another string leak library?

I have some misunderstandings regarding this simple example:

char *s = "abc";
s = "def";

Will assigning a second line cause a memory leak, or will it be replaced properly? If the first is true, how to replace the value correctly s?

+4
source share
3 answers

No. There is no memory leak.

You just changed sto point to another string literal that is good (with the help of this:) s = "def";.

, , malloc/calloc/realloc , ( free(). , POSIX < href= "http://man7.org/linux/man-pages/man3/getdelim.3.html" > getline() ), free().

+6

, . :

char *s = strdup("abc");  // dynamic memory allocation
s = "def";

( ), "abc".

, , .

, char s[] = "abc"; (, ) "def" , :

strcpy(s,"def");

( , : undefined).

+3

:

char *s = "abc";
s = "def";

. char *s - . char *s = "abc", , *s. s "def", , , , *s.

.. . , strcpy(3)/strncpy(3).

- , malloc(3)/strdup(3), .

, :

const char *str1 = "abc";
const char *str2 = "def";

char *s1 = malloc(strlen(str1)+1); /* dynamic memory allocation with malloc() */
char *s2 = malloc(strlen(str2)+1);

s1 = s2;

s1 s2. , , s1 , s1 s2, , . , free(3), . free() , , .

0

Source: https://habr.com/ru/post/1669681/


All Articles