The difference between the declared line and the selected line

I.  char *str = "Stack";

II. char *str = (char*) malloc(6);
    strcpy(str, "Stack");

What are the differences between the two above approaches?

Are they the same or something else behind the curtains?

+5
source share
3 answers

The above code will cause problems.

The first instance is known as static row allocation and definition. For ordinary type variables int, etc. And non-string data types such an announcement will allocate data on the stack. When strings are initialized using string literals (i.e.:), "stack"it is allocated in the read-only part of the memory.

The string itself should not be changed, as it will be stored in the read-only part of the memory. The pointer itself can be changed to indicate a new location.

t

char strGlobal[10] = "Global";

int main(void) {
  char* str = "Stack";
  char* st2 = "NewStack";
  str = str2;  // OK
  strcpy(str, str2); // Will crash
}

, const, :

const char* str = "Stack"; // Same effect as char* str, but the compiler
                           // now provides additional warnings against doing something dangerous

, , . . - free().

, . , , .

char str[] = "Stack";

:

Example:                       Allocation Type:     Read/Write:    Storage Location:
================================================================================
const char* str = "Stack";     Static               Read-only      Code segment
char* str = "Stack";           Static               Read-only      Code segment
char* str = malloc(...);       Dynamic              Read-write     Heap
char str[] = "Stack";          Static               Read-write     Stack
char strGlobal[10] = "Global"; Static               Read-write     Data Segment (R/W)

, . , .


+17

const char*, -.
"Stack" .

II, free.

+2

, - , . (Oooh ..)

case I:you have a pointer strthat points to a read- only memory region (section .rodata) whose contents "Stack".

case II:you have a pointer strthat points to a dynamically allocated area (on the heap), the contents of which "Stack", which can be changed and should be freed by accessing free(str)after using it.

0
source

All Articles