Automatic memory allocation for strings

char* test() {
    char* returnValue = "test";
    return returnValue;
}  
char* test=test();
printf("%s",test);

Is it safe to use? this is the same as

char* test {
    char* returnValue=strdup("test");
    return returnValue;
}
char* test=test();
printf("%s",test);

if so, should I release him later? they both work correctly.

+4
source share
4 answers

- this is the same

No, it is not.


char * test1() {
  char * returnValue = "test";
  return returnValue;
}  

The code above returns a fixed address in a constant literal "test". This will be the same address every time the function is called.

This is not a dynamic memory allocation.

Performance

printf("%d\n", test1() == test1());

will print

1

True, the two returned addresses match.

In "constness"

To better reflect the constancy of the result test1(), it is better to define it as follows:

const char * test1() {
  const char * returnValue = "test";
  return returnValue;
}  

char * test2 {
  char * returnValue = strdup("test");
  return returnValue;
}

, "test" . * 1 .

* 1: "-", test2() ()

. free() , strdup() ( malloc()), , .

printf("%d\n", test2() == test2()); /* leaks memory: 2 times 4+1 char */

0

"false", .

: ,

char * p, * q;
printf("%d\n", (p = test2()) == (q = test2()));
free(p);
free(q);

.

, , "" , .

+3
char* test() {
    char* returnValue = "test";
    return returnValue;
}  

?

, returnValue, . , , - undefined.

- ,

char* test {
    char* returnValue=strdup("test");
    return returnValue;
}

-

strdup()

Returns a pointer to a null-terminated byte string, which is a duplicate of the string pointed to by str1. The returned pointer must be passed to free to avoid a memory leak.

strdup() malloc() , "test". , . , free() , . , , strdup(), .

+2

?

, . , .

- ,

, strdup() .

, ?

, strdup() .

printf() , ... char* returnValue = "test", strdup()

+1

"test" Stack (const char).

"test". , . - , , (munmap_chunk(): invalid pointer , ).

In the second block, you return a pointer to the dynamically allocated part of the memory in the Heap . It is your responsibility to free this part of the memory with free()or equivalent. You can change this variable or even redistribute this part of the memory.

You can always run your own tests:

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

char* test1() {
    char* returnValue = "test";
    return returnValue;
}  
char* test2() {
    char* returnValue = strdup("test");
    return returnValue;
}

int main(void)
{
   char* vtest1 = test1();
   printf("%s => %p\n", vtest1, &vtest1);
   char* vtest2 = test2();
   printf("%s => %p\n", vtest2, &vtest2);

   printf("Freeing 2nd test...\n");
   free(vtest2);

   printf("Trying to modify 1st test...\n");
   vtest1[0] = 'p';
   printf("Freeing 1st test...\n");
   free(vtest1);

   return 0;
}
0
source

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


All Articles