DO and Donts when using pointers

This is a simple but important question. What to do and click when using pointers to C and C ++ to avoid an exception in SEXMENTATION FAULT on AIX?

Where is char * preferable to an array of characters?

+7
c ++ c pointers
source share
10 answers

C ++ specific

  • Avoid manual memory management , use RAII containers like std::auto_ptr , boost::scoped_ptr , boost::shared_ptr and equivalent array containers instead. Even simpler, often std::vector works just fine, and it does not require a pointer at all. Finally, instead of passing pointers to large or modifiable data structures, you can pass references. Pointers can represent arrays, while references avoid this ambiguity.
  • Indexing arrays are a worthy replacement for most arithmetic pointers. As a rule, this is no slower than pointer arithmetic, which often becomes erroneous and harder to read and maintain. As a rule, do not micro-optimize due to readability.
  • Call the correct maladjustment procedure: delete[] intended for arrays allocated only with new ...[] , delete for pointers only to individual objects and free(...) only for memory allocated via C api (for example, malloc(..) ). They should not be confused; Routines for deallocation in C ++ include calls to destructors and, therefore, must be called correctly.
  • Explicitly initialize and set pointless pointers to NULL . It's easier to debug random zero dereferencing than improper memory access. This is normal to free the NULL pointer, so you donโ€™t need to clutter your destructor with checks to avoid this. If you delete an object prematurely, you must set its pointer to NULL in order to avoid double deletion of the same pointer and to avoid accidentally dereferencing a dangling pointer.
  • If you use C ++ inheritance and redefine the destructor, read on virtual destructors; they are necessary for correctness (In short, the base class must explicitly denote the destructor as virtual).
  • Remember who owns the pointer if you must manually manage the memory. Only the owner must free the object or array pointed to by the pointer, and no other object can use the object after the owner delete pointer to it. boost::shared_ptr is a pretty simple overhead container, which is often good when you need to split a pointer.
+18
source share
  • Always make sure your pointers are initialized.
  • Always know the length of the selected memory area
  • Always check for NULL when working with a pointer
  • Always remove pointers after using them.
  • Never overwrite memory at the ends of a pointer
  • Never trust the validity pointers provided by your methods.
  • Never put user input in a pointer (it turns out, for example)
  • Never mix malloc / free with new / remote
  • Never highlight pointers to class objects using malloc
  • Never free class object pointers with free

And last but not least

Never use pointers unless you need to ... There are links (const) to avoid creating a copy of objects passed to functions and STL containers and strings for other storage requirements, and use smart ones (boost :: shared_ptr), if you really need pointers and you don't want to track them manually.

+12
source share

In C

  • Do not indicate that you do not "own."
  • Do not look for NULL pointers.
  • Provide free resources when you don't need them.
  • Do not lose track of your pointers (be careful when overflowing).
  • Do not abuse void* .
  • Do not mix pointer types: a char* is not the same as double** .
  • Check the return value of functions that return pointers.
+3
source share

Record standard compatible code. This should take care of the platform. And many other questions. And use const . This takes care of more problems.

+2
source share

I recently joined a project in which several good developers used only bare pointers. Although they have excellent skills, their program (running on Windows / Linux / HP-UX) occasionally caused segfaults, and there were several memory leaks.

I understand that if the program is quite large and has threads, it is very difficult to find all the errors associated with pointers, and if you absolutely do not need a null pointer, you should use Boost.Smart_ptr .

+1
source share

C ++ always uses virtual destructors. If you remove the base class, this ensures that the destuctor of the derived class is called. If you do not, and the derived class makes some selections, you will not have the opportunity to clear it.

+1
source share

NOTE: C specific answer โ†’

The following are common causes of segmentation or segmentation dysfunction:

Invalid format control string in printf or scanf statements: Make sure that the format control string has the same number of conversion specifiers (% s), since printf or scanf have arguments that should be printed or read accordingly, and that the specifiers match the type of variable that need to print or read. This also applies to fprintf and fscanf.

Forgetting to use "&" on scanf arguments: The scanf function takes as arguments the format control string and the addresses of the variables in which it will put the data that it reads. "&" (address) is used to supply the address of a variable. Usually forget to use "&". with each variable in a scanf call. Omitting "&" can cause segmentation disruption.

Access outside the array: Make sure that you do not violate the boundaries of any array that you use; those. You did not index the array with a value less than the index of its lowest element, or greater than the index of its highest element.

Inability to initialize a pointer before accessing it: A pointer must be assigned a valid address (i.e., appears on the left side of the task) before it is available (i.e. appears on the right of the task). Make sure you point to all pointers to a valid memory location. Correct initialization of the pointer can be done in several ways. Examples are given below.

Misuse of the "&" (address) and "" (dereferencing) statements: Make sure you understand how these statements work. Know when they should be applied and when not to apply. As mentioned above, it is customary to forget to use "&". with each variable in a scanf call. Remember that scanf requires the address of the variables it reads. Especially, you know, when "&" and "" are absolutely necessary, and when it is better to avoid using them.

Troubleshooting:

Check EVERY place in your program that uses pointers, array indexes, or uses the address operator (&) and the dereference operator (*). Each of them is a candidate for causing a violation of segmentation. Make sure you understand the use of pointers and related operators. If the program uses a lot of pointers and has many occurrences of and and *, add some printf statements to determine where the program causes the error and examine the pointers and variables involved in this statement.

Remember that printf statements must have a newline character (\ n) at the end of formatting control lines for debugging purposes to force the print buffer to be flushed.

+1
source share

The issue of ownership is often the most difficult: your design should already decide on this. Anyone who owns the facility must be held responsible for its destruction.

But I saw a script that still mentioned destroyed objects, as well as deceived pointers. Your design should also consider "validity." Each reference to a remote object must be clearly invalid. If I'm not mistaken, the weak_ptr class may delay this decision.

0
source share

Do not perform border checks.

0
source share

Isn't the answer to the question "Where is char * preferable to an array of characters?" question, but one thing that recently bit someone I was considering was "sizeof."

Consider this:

 char *a = new char[3]; char b[3]; 

In many places, you use "a" and "b" in the same way. The problems begin when you do something like:

 strncpy(b, some_string, sizeof(b)); strncpy(a, some_string, sizeof(a)); 

I think the moral of this story is: be careful with sizeof (). It is probably best to maintain a constant dimension.

0
source share

All Articles