Search code examples
cpointersdynamic-memory-allocationc-stringsstring-literals

Dynamic memory allocation and pointers related concept doubts


On the first note: it is a new concept to me!! I studied pointers and dynamic memory allocations and executed some program recently and was wondering in statement char*p="Computers" the string is stored in some memory location and the base address, i.e the starting address of the string is stored in p, now I noticed I can perform any desired operations on the string, now my doubt is why do we use a special statement like malloc and calloc when we can just declare a string like this of the desired length.

If my understanding of the concept Is wrong please explain.

Thanks in advance.


Solution

  • In this declaration

    char*p="Computers";
    

    the pointer p is initialized by the address of the first character of the string literal "Computers".

    String literals have the static storage duration. You may not change a string literal as for example

    p[0] = 'c';
    

    Any attempt to change a string literal results in undefined behavior.

    The function malloc is used to allocate memory dynamically. For example if you want to create dynamically a character array that will contain the string "Computers" you should write

    char *p = malloc( 10 ); // the same as `malloc( 10 * sizeof( char ) )`
    strcpy( p, "Computers" );
    

    You may change the created character array. For example

    p[0] = 'c';
    

    After the array is not required any more you should free the allocated memory like

    free( p );
    

    Otherwise the program can have a memory leak.