0

I know this has been answer before, but I can't find the question.
What are the differences between these two initialisations:

int main() 
{
    char* pch1;
    char* pch2;

    pch1 = (char*)malloc(sizeof(char) * 5);
    strcpy(pch1, "Text");

    pch2 = "Text";
}
Adrian
  • 19,440
  • 34
  • 112
  • 219

4 Answers4

2

There are three main differences here:

  • The first one copies the content of a string literal into dynamic memory, while the second one points to that literal directly.
  • Modifying pch1 string is legal; modifying pch2 string is illegal
  • You need to free pch1 to avoid memory leak.

For completeness, consider pch3 which is initialized like this:

char tmp[] = "Text";
char *pch3 = tmp;

This pch3 is modifiable like your pch1, but it does not need freeing, because the content of the string is copied into automatic memory.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

First: don't cast the return value from malloc - it's a common source of errors. Do I cast the result of malloc?

pch1 = malloc(sizeof(char) * 5);

assigns a pointer to a dynamically allocated block of 5 bytes on the heap.

pch2 = "Text";

should ideally be avoided because it assigns a pointer to a string literal. String literals are read-only on most OSes and is also a common source of mistakes. If you do this you should make the pointer to const

const char * pch2 = "Text";
Community
  • 1
  • 1
Sergey L.
  • 21,822
  • 5
  • 49
  • 75
  • I haven't programmed that much in C, but everywhere I see that the return value from malloc it is cast. Can you tell me why this is wrong? – Adrian Feb 20 '14 at 11:26
  • 1
    In C++ you have to cast, in C you should not. Explained in detail here: http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – Sergey L. Feb 20 '14 at 11:27
1

pch1 points to heap

you can modify it within bounderies

plus you have to free it

other points to static data segment you can not modify it

qwr
  • 3,660
  • 17
  • 29
0
  1. pch1 will use heap memory for storing your data
  2. pch2 - using stack memory