Pointer to string changes its value unexpectedly

后端 未结 4 1522
执念已碎
执念已碎 2021-01-26 18:32

I have noted that, when writing a string in an array allocated with malloc(), its value changes. To be clear, here is the code that replicates this \"error\":

4条回答
  •  忘掉有多难
    2021-01-26 19:11

    Your problem

    You are allocating memory for your pointer with malloc() but then you assign your pointer variable to something else ("something", which has its own address), instead of filling the newly-allocated pointer.

    Solution

    You should use the strdup() function that allocates memory and copies a string at the allocated memory:

    a_p = strdup("something");
    

    Or the strcpy() function, that takes a malloc()'d pointer and a string to copy in the pointed memory:

    a_p = malloc(N * sizeof(char));
    strcpy(a_p, "something");
    

提交回复
热议问题