malloc creates seg faults?

B

Berk Birand

Hi,

For an assignement that I have, I have to write a function that is used
for duplicating arrays of some objects (called Product). It is supposed
to be something similar to strndup, but taking a Product* as an argument
instead of a char*, and of course the length of the array.

However, at some point in my code, where I have to call malloc to
allocate the required memory, I get a Segmentation Fault. Here's what I
have written:

Product* prodndup(const Product* src, size_t n)
{
int length = n * sizeof(Product); // size of memory to be allocated
Product* retval; // pointer to be returned

retval = (Product*) malloc(length); // <= this is the point

if (retval == NULL) return NULL;

Product *p = retval;

while (n > 0)
{
*p = *src;
p++;
src++;
n--;
}


return retval;
}

When I uncomment the marked line, the program terminates (although of
course, without doing what it is supposed to do).

What am I doing wrong? Isn't this how malloc is supposed to be called?

Thanks,
BB
 
B

Berk Birand

Seems like you have a problem before the call to malloc. Can you post a
minimal program that demonstrates your problem ? Tools like Rational Purify
or valgrind can also help here.

Sharad

I had some other unrelated code working before. After learning that
those maybe flawed I commented all out. Now here's what I have in my
main program, along with the function definition.

I also installed valgrind and tried running memcheck on it. It ended
with apparently 34 errors in 15 contexts. Here's that output:

==31275== LEAK SUMMARY:
==31275== definitely lost: 0 bytes in 0 blocks.
==31275== possibly lost: 640 bytes in 1 blocks.
==31275== still reachable: 32 bytes in 2 blocks.
==31275== suppressed: 0 bytes in 0 blocks.
==31275== Reachable blocks (those to which a pointer was found) are not
shown.
==31275== To see them, rerun with: --show-reachable=yes
Segmentation fault

And here's the code:

#include <iostream>
#include <string.h>
// string.h covers the C-style string functions.
#include "product.h"

using namespace std;

Product* prodndup(const Product* src, int n);

int main()
{

printf("\n\nManipulating products\n");

Product *prod1 = new Product("a",12,32);
Product *prod2;


printf("Before dup, pointer prod2 = %p, contents =\n", prod2);

prod1->print();
prod1->print();

prod2 = prodndup(prod1 , 1); // <-- Problem here

printf("Pointer prod2 = %p, contents =", prod2);
//prod2->print();

return 0;
}

Product* prodndup(const Product* src, int n)
{
int length = n * sizeof(Product); // size of memory to be allocated
Product* retval; // pointer to be returned

retval = (Product*) malloc(length);

if (retval == NULL) return NULL;

Product *p = retval;

while (n > 0)
{
*p = *src;
p++;
src++;
n--;
}


return retval;
}


Thanks a lot for both of your helps!
 
B

Berk Birand

What am I doing wrong? Isn't this how malloc is supposed to be called?

I was just wondering, if there wasn't any previous mistakes in the code,
would that function work as expected? Are we positive that the "leak"
is not in that function??

Thanks again,
BB
 
L

Larry Brasfield

[snip]
And here's the code:
[snip]
Product* prodndup(const Product* src, int n)
{
int length = n * sizeof(Product); // size of memory to be allocated
Product* retval; // pointer to be returned

retval = (Product*) malloc(length);

if (retval == NULL) return NULL;

Product *p = retval;

while (n > 0)
{
*p = *src;
p++;
src++;
n--;
}


return retval;
}


The above code uses the Product assignment operator
to give an initial value to what malloc() has returned.
This is incorrect. Assignment should only be done to
already constructed objects. Using it on raw memory
is likely to lead to the kinds of problems you mention
in the subject line.

If you insist on using malloc() rather than array new,
then you need to use placement new to get the Product
ctor to be executed on each block of raw memory that
is to become a Product object. Then you can assign
to it. Alternatively, you can use placement new and
the Product copy ctor, if it has one.
 
L

Larry Brasfield

Berk Birand said:
Larry said:
[snip]



The above code uses the Product assignment operator
to give an initial value to what malloc() has returned.
This is incorrect. Assignment should only be done to
already constructed objects. Using it on raw memory
is likely to lead to the kinds of problems you mention
in the subject line.

If you insist on using malloc() rather than array new,
then you need to use placement new to get the Product
ctor to be executed on each block of raw memory that
is to become a Product object. Then you can assign
to it. Alternatively, you can use placement new and
the Product copy ctor, if it has one.

Hmm, this is awfully interesting. The professor hadn't mentioned this problem. The problem with new is that I need dynamic
allocation. The size of the array is not known beforehand, and as far as I know, new doesn't accept variables.

Array new does.
If 'SomeType' is a type name, (such as float, or 'Product' where
you defined "class Product { ... }" somewhere), then you can
get an array of SomeType objects by writing:
SomeType * gobOfObjects = new SomeType[howMany];
where 'howMany' names an integer with a positive value.
Just remember to dispose of it via
delete [] gobOfObjects;
or an equivalent on the same pointer value.
So, in the light of this new idea, what am I supposed to do??

Having not seen your assignment, I'm not sure. But if your
professor, when shown my post, does not agree with my
criticism of the quoted code, then you should double check
everything he/she says with a more reliable reference.

I would be remiss not to mention that using std::vector<Product>
would be a better solution than rolling your own array memory
management, as your posted code apparently represents. If
you were to look at the code for std::vector, you would see
use of placement new as I mentioned.
 
G

guilt

Larry said:
Berk Birand said:
Larry said:
[snip]



The above code uses the Product assignment operator
to give an initial value to what malloc() has returned.
This is incorrect. Assignment should only be done to
already constructed objects. Using it on raw memory
is likely to lead to the kinds of problems you mention
in the subject line.

If you insist on using malloc() rather than array new,
then you need to use placement new to get the Product
ctor to be executed on each block of raw memory that
is to become a Product object. Then you can assign
to it. Alternatively, you can use placement new and
the Product copy ctor, if it has one.

Hmm, this is awfully interesting. The professor hadn't mentioned this problem. The problem with new is that I need dynamic
allocation. The size of the array is not known beforehand, and as
far as I know, new doesn't accept variables.
Array new does.
If 'SomeType' is a type name, (such as float, or 'Product' where
you defined "class Product { ... }" somewhere), then you can
get an array of SomeType objects by writing:
SomeType * gobOfObjects = new SomeType[howMany];
where 'howMany' names an integer with a positive value.
Just remember to dispose of it via
delete [] gobOfObjects;
or an equivalent on the same pointer value.
So, in the light of this new idea, what am I supposed to do??

Having not seen your assignment, I'm not sure. But if your
professor, when shown my post, does not agree with my
criticism of the quoted code, then you should double check
everything he/she says with a more reliable reference.

I would be remiss not to mention that using std::vector<Product>
would be a better solution than rolling your own array memory
management, as your posted code apparently represents. If
you were to look at the code for std::vector, you would see
use of placement new as I mentioned.
 
P

Peter Koch Larsen

Berk Birand said:
Hi,

For an assignement that I have, I have to write a function that is used
for duplicating arrays of some objects (called Product). It is supposed to
be something similar to strndup, but taking a Product* as an argument
instead of a char*, and of course the length of the array.
This is an assignment from some class? Go tell your teacher that this is not
C++.

Here, you would copy two arrays of products like this:

std::vector<Product> p1; // first array - using the "built-in" vector
std::vector<Product> p2(p1); // create a vector and make it the same as
your previous array.

// you could also use p2 = p1 if that would be more convenient.
However, at some point in my code, where I have to call malloc to allocate
the required memory, I get a Segmentation Fault. Here's what I have
written:

Product* prodndup(const Product* src, size_t n)
{
int length = n * sizeof(Product); // size of memory to be allocated
Product* retval; // pointer to be returned

retval = (Product*) malloc(length); // <= this is the point

retval does not point to Product here as there malloc returns raw memory.
As an alternative you could have use retval = new Product[n];
if (retval == NULL) return NULL;

Product *p = retval;

while (n > 0)
{
*p = *src;

As *p is not a Product this assignment is meaningless. Assignment assumes a
valid object.
p++;
src++;
n--;
}


return retval;
}

When I uncomment the marked line, the program terminates (although of
course, without doing what it is supposed to do).

What am I doing wrong? Isn't this how malloc is supposed to be called?
Nope. You are not supposed to call malloc at all in C++ code that YOU
create. malloc is there for backward compatibility.
Thanks,
BB

/Peter
 
A

Artie Gold

Berk said:
I had some other unrelated code working before. After learning that
those maybe flawed I commented all out. Now here's what I have in my
main program, along with the function definition.

I also installed valgrind and tried running memcheck on it. It ended
with apparently 34 errors in 15 contexts. Here's that output:

==31275== LEAK SUMMARY:
==31275== definitely lost: 0 bytes in 0 blocks.
==31275== possibly lost: 640 bytes in 1 blocks.
==31275== still reachable: 32 bytes in 2 blocks.
==31275== suppressed: 0 bytes in 0 blocks.
==31275== Reachable blocks (those to which a pointer was found) are not
shown.
==31275== To see them, rerun with: --show-reachable=yes
Segmentation fault

And here's the code:

#include <iostream>
#include <string.h>
// string.h covers the C-style string functions.
#include "product.h"

using namespace std;

Product* prodndup(const Product* src, int n);

int main()
{

printf("\n\nManipulating products\n");

Product *prod1 = new Product("a",12,32);
Product *prod2;


printf("Before dup, pointer prod2 = %p, contents =\n", prod2);

prod1->print();
prod1->print();

prod2 = prodndup(prod1 , 1); // <-- Problem here

printf("Pointer prod2 = %p, contents =", prod2);
//prod2->print();

return 0;
}

Product* prodndup(const Product* src, int n)
{
int length = n * sizeof(Product); // size of memory to be allocated
Product* retval; // pointer to be returned

retval = (Product*) malloc(length);

if (retval == NULL) return NULL;

Product *p = retval;

while (n > 0)
{
*p = *src;
p++;
src++;
n--;
}


return retval;
}


Thanks a lot for both of your helps!

Just a stab in the dark (with no dispute about everything mentioned
elsethread): What does the constructor for `Product' look like? I
suspect *that's* where the immediate difficulty lies (but use operator
new for objects -- or, better, use a std::vector instead of an array,
etc. etc.). ;-)

HTH,
--ag
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top