C++ help?

Joined
Mar 3, 2003
Messages
726
I haven't used C++ for years, and the one thing I can't figure out how to do is to return a pointer to an object from a function. I need to create a new object in the function, and return a pointer to it, that won't be pointing to empty space. Right now I have it sort of working by throwing huge amounts of memory at the pointers with malloc(), but that's wrong on so many levels, and does not work all the way either.

Any tips?
 
Your function header should look like this so your function will be returning a pointer:

ObjectName* functionname( parameters);

Inside the definition you can then do this:

{
ObjectName* anObject = new ObjectName;

return anObject;
}


Where ObjectName is the name of the class or whatever your object is, and "anObject" is a randomly chosen variable name. The new keyword dynamically allocates memory and "anObject" gives you a handle on that memory.
 
I am sooo happy that I am not a programmer and don't use C++.

Actually I think it would be nice to know better, but that's just not how I'd want to spend my time. But I'm gratified to see that someone on the board was able to answer it quickly!
 
Thanks! I think that did it. I'm still getting the occasional segmentation fault, but it's probably from something else at this point. I think this thing might just work.
 
Beware of mixing malloc and new. If you are using/creating C++ classes, stick to new and delete. Using malloc to allocate memory for classes will not call class constructors and can lead to extremely strange memory bugs.
 
Just a quick question. What are you writing your code for? School? Fun?! :rolleyes: Work? Just curious.
 
enkidu said:
Beware of mixing malloc and new. If you are using/creating C++ classes, stick to new and delete. Using malloc to allocate memory for classes will not call class constructors and can lead to extremely strange memory bugs.
Yep, that's right. Also, when you just need buffers for repetitive operations, and you use a Mikrosoft compiler, avoid using new and delete and stick with malloc and free (or GloballAlloc)! I had a small but persistent memory leak in a program that took me quite a while to sort out. It was because each time I used a new-delete cycle for allocating a small char* buffer, it leaked a few bytes ...
 
I had a small but persistent memory leak in a program that took me quite a while to sort out. It was because each time I used a new-delete cycle for allocating a small char* buffer, it leaked a few bytes ...
Garh! Repressed memories of crap Visual Studio stl and IEEE 754 implementations surfacing! find a happy place, find a happy place, find a happy place... Oh yeah, I write Linux code now, I am in a happy place :)

Good luck with your school work, James. If you are hoping to become a coder, I would give you one piece of advice; beware of the siren call of the debugger; read the source, join the source, direct the source. The coders I respect the most use the debugger only as a tool of absolute last resort.
 
To be honest, I have never used a debugger. I think I should look into it, though.

Also, my project won't run on my windows laptop. I had it running fine in Mepis Linux, but now I can compile the source fine on my laptop using either Dev-C++ or g++ for cygwin, but now I get segmentation errors on this line:

flights = (Flight *) malloc(numFlights * sizeof(Flight *));

where Flight is a class. Is that the proper way to make an array of objects?
 
Nice to see that there are some C++ folks around here. It was my primary language used at NCSU and we used it quite a lot at AT&T/Lucent.

I do mostly Java and C# now, for coding languages, but C++ sure has some good memories.

Ya'll have fun, keep you pointers straight and memory tight. I'm really going to enjoy having templates widely implemented in Java, it's going to freak out a lot of newbies.
 
Cmd, what environment are you working in?

I use VS .NET 2003 for C# and VB. Have used C# for Sharepoint but mostly work in VB.
 
James Muehlner said:
To be honest, I have never used a debugger. I think I should look into it, though.

Also, my project won't run on my windows laptop. I had it running fine in Mepis Linux, but now I can compile the source fine on my laptop using either Dev-C++ or g++ for cygwin, but now I get segmentation errors on this line:

flights = (Flight *) malloc(numFlights * sizeof(Flight *));

where Flight is a class. Is that the proper way to make an array of objects?
I'm not sure if this is the problem or not, but I've always been told never to use malloc for a class. Malloc was for the C language, when classes did not exist, and that can cause problems. I've never used malloc, though, so I can't say for sure if the above line is good or not. I would create an array of Flight objects like this, assuming that is what you're trying to do:

Flight * flights;
flights = new Flight[number of objects in array];

flights would then give you a pointer to the first object in the array, and you can use array notation to access the rest, or increment the pointer.
 
Nordic Viking said:
Cmd, what environment are you working in?

I use VS .NET 2003 for C# and VB. Have used C# for Sharepoint but mostly work in VB.

Hi Nordic Viking,
Here is what I work with now:

C# for GUIs on the desktops inside the intranet (no IIS), JSPs for GUIs exposed externally, Java mostly for new development in the back end, Web Services in the middle. A whole bunch of UNIX servers for lots of things, a mainframe for COBOL and DB2, and lots of Windows servers.

So far it meets the current needs of being deliverable, secure, and flexable. So far we have not needed to outsource any IT departments to meet goals. Hope that continues!
 
(Flight *) malloc(numFlights * sizeof(Flight *));
As noted above, you should allocate memory for objects with new, since that will call the proper constructors. But, if Flight were a struct, you would allocate an array of them like

Flight * arrflight = (Flight *) malloc(numFlights * sizeof (Flight));

sizeof evaluates to the the memory size of the passed in struct, and you are passing in a pointer, typically the same size as int. BUT, since Flight is a C++ class, you should never use malloc. Murnax's example is correct for allocating an array of objects.
 
Thanks for all the help guys. That did help a lot, but I just realized I think where all the errors are coming from. I brought the source code home, but not the files it reads from. Woops. Now I feel like a doofus. :foot:
 
Ok, one more question. I have to create a two dimensional array of strings (char ***). And It does not seem to be making it correctly. (Meaning that when I put these things inside classes, which then go in an array, they seem to be pointing to the same memory location).

What I am doing, basically, is this:

Code:
passengers = (char ***) (malloc(numRows * sizeof(char **)));

for(int i = 0; i < numRows; i++)
    passengers[i] = (char **) (malloc(widthRows * sizeof(char *)));

  for(int i = 0; i < numRows; i++) // fills the seats with empty names
    for(int j = 0; j < widthRows; j++)
      passengers[i][j] = "";

  for(int j = 0; j < numReservedSeats; j++)
  {  
    fscanf(fp, "%i%c ", &seatNum, &seatLetter);
    readLine = fgets(readLine, 1000, fp);
    char * name = (char *) malloc(strlen(readLine));
    strcpy(name, readLine);
    name[strlen(name) - 1] = '\0'; // removes the newline
    seatLetterNum = toupper(seatLetter) - 65;
    seatNum -= 1; // subtracts 1 to get the index
    passengers[seatNum][seatLetterNum] = name;
  }
Am I making ***passengers the wrong way somehow? Any Help?
 
Anyone? I compiled it in both windows and linux, and it doesn't work correctly in either, but in windows not ALL of the pointers point to the same memory location, just some of them. I am massively confused.
 
Here's my review of your code. Keep in mind that I haven't taught a programming class in about 10 years so don't take it personally if I'm direct in my points.

From a high level perspective, is there a reason you're not using the C++ String class and the stl containers vector or map? Using them could make your code much easier to write. If your class doesn't prevent you from doing so, I would strongly urge you to look into using the stl container classes and String to do the operations you are trying to do.

Mid-level problems I see:

  • First 'passengers[j] = "";' will not work because you can't copy c strings that way. You should probably be assigning NULL instead of ""; "" is the memory location of the char* "\0" at that point in the code.[*]Second, you need to allocate strlen + 1 to get the string in properly, OR strip the newline from the readLine variable before strcpy'ing to name. [*]Third, you're not doing any bounds checking on seatNum and seatLetter or seatLetterNum to make sure that they are within the array bounds.

Low-level nits:
  • name is not a very good variable name. Probably seatName would be better.
  • readLine is not a very good variable name either (at least for me, because it collides with the readline library function readline). readBuffer or something similar would be better.
  • I don't see readLine decleared/allocated anywhere. Probably easiest would be to allocate it on the state with something like char readLine[1000];
  • Instead of substracting 65, it would be clearer if your subtract 'A' since that makes it clear that A->0, B->1 etc.
  • If your name variable happens to be as long as 999 characters or longer, the last character will not be a newline, but you'll overwrite it anyway.
  • You aren't checking the return values of fgets or fscanf or malloc.
  • Your indentation is wrong for the first three lines :).

that aside, I don't see anything where it would cause all of the elements in passengers to point to the same memory location (since name gets a fresh malloc everytime through the loop) except for the "" being assigned to passengers[j] during initialization. Perhaps your classes are not being created properly? Do you have any class static member variables?
 
Back
Top