LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Of pointers - seg faults, memory leaks and assorted troubles (https://www.linuxquestions.org/questions/programming-9/of-pointers-seg-faults-memory-leaks-and-assorted-troubles-470273/)

vharishankar 08-02-2006 10:27 PM

Of pointers - seg faults, memory leaks and assorted troubles
 
As I understand it, this code would lead to a segfault in Linux and probably unexpected behaviour in OSes where there is no concept of "protected memory". Am I right?

Code:

char *str; /* Don't initialize the pointer - it is initialized to some random memory location */
strcpy (str, "something is the problem"); /* Assign the pointer */

Now this code:
Code:

void func1 ()
{
  char *str = new char[50];
  func2 (str);
  strcpy (str, "Something else");
}

void func2 (char* value)
{
  delete[] value; /* delete is called on a pointer that's got as a parameter */
}

This would also lead to unexpected or dangerous consequences, right?

Or a classic memory leak scenario:

Code:

int* array = new int[100];
...
...
int* newarray = new int[10];
array = newarray; /* the old array is lost */

Can you think of any more situations where pointers would lead to memory leaks or other complex, hard to resolve problems?

sundialsvcs 08-03-2006 07:33 AM

Ask your instructor?

vharishankar 08-03-2006 07:47 AM

DECLARATION:

I don't have one (an instructor). I'm not asking for homework help. I left school about 8 years ago. I'm a hobbyist programmer. I love dabbling with C/C++. I'm not a school kid. I'm doing my MBA now. I just want to discuss pointers and their intricacies in different compilers with fellow C/C++ programmers out of academic curiosity.

/END DECLARATION

dmail 08-03-2006 08:18 AM

You have missed the obvious one.
Code:

void func()
{
int* a = new int;
}

Smart pointers help avoid these problems.


All times are GMT -5. The time now is 11:27 AM.