user1242967
user1242967

Reputation: 1290

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.

Upvotes: 1

Views: 80

Answers (2)

deinst
deinst

Reputation: 18782

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);

Upvotes: 3

Deepu
Deepu

Reputation: 7610

The following line causes the error,

tempQuestion.link = "stackoverflow.com";

Instead copy as follows,

strcpy(tempQuestion.link, "stackoverflow.com");

Upvotes: 1

Related Questions