6 Replies - 1073 Views - Last Post: 04 July 2010 - 12:03 PM Rate Topic: -----

#1 benbraide  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 31-January 10

Help with pointers and Dynamic memory allocations

Posted 02 July 2010 - 08:22 AM

Hi, I tried writting a program that is supposed to behave like the "string" class using pointers and dynamic memory allocations. It compiles but on run time it either stops working or i get wrong results. And if I try debugging, at some point it pops up an error. This is part of the code with the fault:
#include <iostream>

using namespace std;

typedef unsigned int u_int;
typedef char* strings;

class sTring
{
private:
	void clean(char * head)
	{
		int j = 0;
		while (head[j] != '\0')
		{
			//this statement helps avoid an unexplainable side effect
			if (sTring::isalpunum(head, j) == false)
				head[j] = '\0';//delete the item
			j++;
		}
	}
	void alloc(char *& ptrs)
	{
		ptrs = new char;//dynamic allocation
		//ptrs = NULL;
	}
	void dealloc(char *& loc)
	{
		delete loc;
	}
public:
	char * ptr;//pointer to the address of the variable
	sTring()
	{
		ptr = NULL;
	}
	//get data from keyboard
	void getline(istream&, char *&);
	//print data to screen
	void prints(ostream&, char *);
//length of string
	u_int length(char *);
}str;
void sTring::prints(ostream& screen, char * loc)
{
	int i = 0;
	//'\n' terminates if it is keyboard input
	//'\0' terminates if it is initialized
	while (loc[i] != '\n' && loc[i] != '\0')
	{
		screen << loc[i];
		i++;
	}
	screen << "\n\n";
}
void sTring::getline(istream& import, char *& line)
{
	int count = -1;
	u_int len = size;
	if (line != NULL)
		sTring::dealloc(line);
	sTring::alloc(line);
	//while the ENTER key is not pressed
	do
	{
		count++;
		import.get(line[count]);
	}while (line[count] != '\n');
	sTring::clean(line);
	while (sTring::length(line) > count)
	{
		line[count] = '\0';
	}
}
u_int sTring::length(char * str)
{
	u_int length = 0, sub = 0;
	//'\n' terminates if it is keyboard input
	//'\0' terminates if it is initialized
	while (str[length] != '\0' && str[length] != '\n')
	{
		if (!(sTring::isalpunum(str, length)))
			sub++;
		length++;
	}
	return length - sub;
}
bool sTring::isalpunum(char * loc, u_int pos)
{
	//ASCII values from SPACE(32) to ~(126)
	if (int(loc[pos]) >= 32 && int(loc[pos]) <= 126)
		return true;
	else
		return false;
}
int main ()
{
	strings str2 = NULL, str3 = NULL, str4;
	str.prints(cout, "Enter anything below lol->\n\n");
	str.getline(cin, str2);
	cout << endl;
	str.getline(cin, str3);
	cout << endl;
	str.prints(cout, str2);
	str.prints(cout, str3);
	return 0;
}

Please I really need some help on this. Thanks.

Is This A Good Question/Topic? 0
  • +

Replies To: Help with pointers and Dynamic memory allocations

#2 KYA  Icon User is offline

  • g++ jameson.cpp -o beverage
  • member icon

Reputation: 3101
  • View blog
  • Posts: 19,141
  • Joined: 14-September 07

Re: Help with pointers and Dynamic memory allocations

Posted 02 July 2010 - 09:01 AM

What's the exact error/message?


Some thoughts after reading your code:

1. Pick a naming convention and stick with it. I prefer class names that start with capitals. The name after the ending bracket of the class isn't really used for C++ classes, structs yes. Not illegal, but not really something people do, there's no need, you just use the class name.
2. Memory allocation should happen in the constructor, currently it only sets the pointer to NULL, not really helpful. There's no guarantee the user will call the next function that actually allocates, speaking of which...
3. Your allocation allocates space for exactly one character. That's not a string. It explains why you're segfaulting all over the place.
4. What is 'strings'? You declare and initialize three of them to NULL in main, where is that class definition? Typo? Didn't notice the typedef.
5. Passing around pointer references is indicative of poor design. While they are useful, you have them everywhere. The outside world should not have direct access to your "internals" (aside from traditional accessors/mutators as needed).
Was This Post Helpful? 1
  • +
  • -

#3 benbraide  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 31-January 10

Re: Help with pointers and Dynamic memory allocations

Posted 02 July 2010 - 09:25 AM

View PostKYA, on 02 July 2010 - 08:01 AM, said:

What's the exact error/message?


Some thoughts after reading your code:

1. Pick a naming convention and stick with it. I prefer class names that start with capitals. The name after the ending bracket of the class isn't really used for C++ classes, structs yes. Not illegal, but not really something people do, there's no need, you just use the class name.
2. Memory allocation should happen in the constructor, currently it only sets the pointer to NULL, not really helpful. There's no guarantee the user will call the next function that actually allocates, speaking of which...
3. Your allocation allocates space for exactly one character. That's not a string. It explains why you're segfaulting all over the place.
4. What is 'strings'? You declare and initialize three of them to NULL in main, where is that class definition? Typo?
5. Passing around pointer references is indicative of poor design. While they are useful, you have them everywhere. The outside world should not have direct access to your "internals" (aside from traditional accessors/mutators as needed).

Memory gets allocated when the "getline" function is called but as for allocating memory for just one character - the program expands it to accept more characters. I don't intend to use the "string" class because that's what i'm trying to reproduce. "char*" was typedefed to "strings". Finally, passing the pointers as arguments was the only possible way i could access the variables from the main - or at least, to the extent of my scope of c++.
Was This Post Helpful? 0
  • +
  • -

#4 KYA  Icon User is offline

  • g++ jameson.cpp -o beverage
  • member icon

Reputation: 3101
  • View blog
  • Posts: 19,141
  • Joined: 14-September 07

Re: Help with pointers and Dynamic memory allocations

Posted 02 July 2010 - 09:38 AM

Ok, but your string doesn't ever get larger then one space, at least in terms of available dynamically allocated memory.


Every time ptrs = new char; the handle to the old memory is gone. All you have is one new 'slot'.

Since 'strings' are char*, you aren't allocating any space for them.


The real issue I have with this, is that you say you are making this class to act as a replacement for std::string, but it isn't treated as an object. At best [here], a static factory.

You are passing third party char pointers via static class calls.
Was This Post Helpful? 1
  • +
  • -

#5 benbraide  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 31-January 10

Re: Help with pointers and Dynamic memory allocations

Posted 02 July 2010 - 09:46 AM

View PostKYA, on 02 July 2010 - 08:38 AM, said:

The real issue I have with this, is that you say you are making this class to act as a replacement for std::string, but it isn't treated as an object. At best [here], a static factory.

You are passing third party char pointers via static class calls.

I'm just learning classes, pointers, and dynamic memories - in fact, this is the first program I'm doing with them. I didn't get your point - strange to me, sadly.
Was This Post Helpful? 0
  • +
  • -

#6 Bench  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 855
  • View blog
  • Posts: 2,338
  • Joined: 20-August 07

Re: Help with pointers and Dynamic memory allocations

Posted 03 July 2010 - 01:14 AM

Think about how you would use the C++ string type
string foo;
foo = "hello";
cout << foo; 

Which you could rewrite without the operators
    string foo;
    foo.assign("hello");
    cout.write(foo.c_str(), foo.size()); 

the C++ string stores the data, and provides an interface to access and modify that data; most importantly, there are no char* or char[] variables floating around in the code which uses string, because that data is encapsulated - in other words, the way in which the C++ string type is designed does not expose its internals to the outside world.


These issues are nothing whatsoever to do with pointers or arrays - they are issues of data abstraction (i.e. writing a user-friendly class - this is the foundation of Object orientation); If you aren't familiar with these concepts, then writing a class using pointers/arrays is a step too far for you at the moment. Get to grips with classes first, and worry about pointers later; if learning classes is equivalent to learning how to switch on a car engine, then learning dynamic memory management is like learning to reverse around a corner.

One thing you could try is writing your class initially using the C++ string type (remember not to let the underlying type become exposed to the outside world). Afterwards, substituting char* for string should be a little easier.

This post has been edited by Bench: 03 July 2010 - 01:18 AM

Was This Post Helpful? 1
  • +
  • -

#7 Guest_jnz*


Reputation:

Re: Help with pointers and Dynamic memory allocations

Posted 04 July 2010 - 12:03 PM

I always find it easier to use C++'s normal keywords instead of adding typedefs all over the place. I'l give you something to get you started but I can't access a compiler at the moment so you will probably have to fix a few errors.

I stick to prefixing _ for my member variables, I try to stick to using the same things all the time.
class Str
{
   char *_Data;
   unsigned int _Length;

public:

   Str()
   {
      this->_Data = 0;
      this->_Length = 0;
   }
   ~Str()
   {
      free((void *)this->_Data); //Even if _Data is NULL this is safe.
      this->_Data = 0;
      this->_Length = 0;
   }

   Str(const Str &copy)
   {
      //copy ctor here
   }

   void Assign(const char *str)
   {
      assert(str);
      assert(this->_Data);
      if(this->_Data)
      {
          free((void *)this->_Data);
          this->_Data = 0;
      }
      this->_Data = strdup(str); //strdup uses malloc so we use free when we are finished.

      assert(this->_Data);

      this->_Length = strlen(this->_Data);  
   }

   void Concatenate(const char *str)
   {
      assert(str);       

      //ok we need the length of our string (this->_Length) and the length of the string to concatenate and 1
      this->_Length += strlen(str);
      this->_Data = (char *)realloc((void *)this->_Data, this->_Length + 1);

      assert(this->_Data);

      strcat(this->_Data, str);
   }
};


Was This Post Helpful? 0

Page 1 of 1