Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to solve the problem of errors in C language printing character garbled and char* character cyclic assignment

Shulou Source: shulou.com Published: 2022-06-01 21:40:44 10月15日 Update

This article introduces the relevant knowledge of "how to solve the error problem of c language printing character garbled and char* character loop assignment". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. Print character garbled

# include # include char * SYM= "; void change () {char tmp [10] =" SYM "; printf ("% d\ n ", tmp); SYM=tmp;} int main (int argc, char * argv []) {change (); printf ("% d\ n ", SYM); printf ("% s\ n ", SYM); return 0;}

Solution:

Tmp [10] is the memory space allocated in the subfunction. When you return to the main function, you have to refer to that piece of memory that has been destroyed. The printed code must be garbled.

The main reason is that the space allocated by the sub-function is in the stack (the string content pointed to by tmp and tmp). After the end of the sub-function, the stack is destroyed and all the space is released.

If you change it to char * tmp, there will be no garbled code. The variable (tmp) in the function is still in the stack, but the string content pointed to by tmp is allocated in the heap.

After the end of the sub-function, the stack is destroyed and all the space is released. However, the content of the string pointed to by tmp still exists, and the address is stored in SYM, which can be accessed.

However, this part of the heap space is already unallocated space (junk space) and can be reallocated at any time. So it's accessible, but it's not secure.

If you must, define char tmp [10] outside the function.

2.charl * single character assignment

# include # include char* p = ""; int main () {int I; / / p = (char*) malloc (8); for

Tags: Character space function allocation garbled memory content error string pointing language problem loop single scheme more comments knowledge solution practical Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information Shulou Tech Info Docker vpn NVidia