Search code examples
carrayspointersdynamic-memory-allocation

Unexpected result while assigning value to a character array in dynamic memory allocation


The following program is showing unexpected result

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

int main()
{
    char* num1;
    num1 = malloc(100*sizeof(char));
    num1 = "38462879";
    printf("%s\n",num1);
    num1[0]='5';
    printf("%s\n",num1);
    return 0;
}

I expect it to print the given string and then print the given string with the first letter replaced by 5 instead of 3 in the next line.

But it is printing the given string in first line and then the program is not going ahead.

Can you please help??


Solution

  • By saying

     num1 = "38462879";
    

    you're essentially

    • Overwriting the allocated pointer to the memory (memory leak)
    • Making num1 point to a string literal. (illegal to attempt to modify the content)

    Later your attempt to modify a part of that literal will invoke undefined behavior. What you need instead is to use strcpy(), like

     strcpy (num1, "38462879");
    

    That said, couple of general suggestion:

    • for a hosted environment, int main() should at least be int main(void).
    • You must always check for the success of a function call (esp. library functions) before using the returned value.
    • in C, sizeof(char) is defined to be 1, it's a redundant multiplier.