Freeing malloc will not erase char data

前端 未结 4 1912
悲&欢浪女
悲&欢浪女 2021-01-29 07:27

I made a smaller scenario of my bigger problem. What I try to do is pass a string to a function which will make a new string out of it. However I ran into some problems.

4条回答
  •  遇见更好的自我
    2021-01-29 08:23

    string* newStr=malloc(sizeof(string)); // malloc a newStr
    strcpy(*newStr, msg);            // copying msg to newStr
    

    This will also crash. string is a pointer so sizeof of it will return 4 or 8, not what you wanted to do.

    Ok, forget about my remark you made a typedef, but I let it here to show you why the typedef is a bad idea. At first glance it obfuscated the fact that it was an array and not a pointer, on a 30 line program it's not a probleme, but when you have to maintain a 200 000 lines project (as I do), you will start to hate these kind of things.

    Another point, you should avoid to work with fixed sized strings of 1024 bytes. 1024 is not that big (even homecomputer of the 80s had screens bigger than that) and for the majority if strings, which are fairly short, you spoil a lot of memory for nothing.

提交回复
热议问题