简体   繁体   中英

strcat function not working with pointers

int main(int argc , int *argv[]){

char str[7] = "Mobile";
char str2[11] = "Samsung4g";

char *str3 = 0;
str3 = ( char* )(malloc(30));

str3 = "Carrier";

strcat(str3, str);//Problem facing here, dunno why

Like what others have mentioned in the comments, the statement:

str3 = "Carrier";

overwrites the value of str3 with the address of the string literal "Carrier" causing the address returned by malloc() to be lost.

Using str3 then in strcat() as a first argument attempts to modify a string literal which results in undefined behaviour.

Use strcpy() or equivalent functions to copy strings in C.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM