Search code examples
cdynamic-memory-allocation

C dynamic memory / C string


This is something similar to what I am trying to do (I skipped code which checks if memory was allocated):

    sscanf(line, "%[^\"]\"%[^\"]", tempString, tempString);
    int length = strlen("stackoverflow.com") + strlen(tempString);
    tempQuestion.link = (char *)malloc((length + 1) * sizeof(char));
    tempQuestion.link = "stackoverflow.com";
    strcat(tempQuestion.link, tempString);

Program crashes after it reaches strcat. I can't figure out what could possibly be wrong.


Solution

  • When you assign tempQuestion.link = "stackoverflow.com" you change the pointer tempQuestion.link. You want to use strncpy to copy the string.

    Change the last two lines to

    strncpy(tempQuestion.link, "stackoverflow.com", length);
    strcat(tempQuestion.link, tempString);