473,480 Members | 1,857 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

malloc creates seg faults?

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
Jul 23 '05 #1
7 1315
"Berk Birand" <gr******@yahoo.com> wrote in message
news:1108357762.05636e8fef4de605858860b6ab18c07c@t eranews...
Larry Brasfield wrote:
"Berk Birand" <gr******@yahoo.com> wrote in message
news:1108355721.1538885266d9be3798d4ce31daa7e0a7@t eranews...
[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.

--
--Larry Brasfield
email: do***********************@hotmail.com
Above views may belong only to me.
Jul 23 '05 #2
> 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!
Jul 23 '05 #3
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
Jul 23 '05 #4

Larry Brasfield wrote:
"Berk Birand" <gr******@yahoo.com> wrote in message
news:1108357762.05636e8fef4de605858860b6ab18c07c@t eranews...
Larry Brasfield wrote:
"Berk Birand" <gr******@yahoo.com> wrote in message
news:1108355721.1538885266d9be3798d4ce31daa7e0a7@t eranews...
[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.

--
--Larry Brasfield
email: do***********************@hotmail.com
Above views may belong only to me.


Jul 23 '05 #5
"Berk Birand" <gr******@yahoo.com> wrote in message
news:1108355721.1538885266d9be3798d4ce31daa7e0a7@t eranews...
[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.

--
--Larry Brasfield
email: do***********************@hotmail.com
Above views may belong only to me.
Jul 23 '05 #6

"Berk Birand" <gr******@yahoo.com> skrev i en meddelelse
news:1108352961.3e5d5b911d946538199f103e3960f28c@t eranews...
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
Jul 23 '05 #7
Berk Birand wrote:
> 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!


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
--
Artie Gold -- Austin, Texas
http://it-matters.blogspot.com (new post 12/5)
http://www.cafepress.com/goldsays
Jul 23 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
1635
by: afarah | last post by:
Under what condition will we see a segmentation fault in the malloc library routine? Specifically, a failure in call to "chunk_alloc()" from within malloc. I have a multi-threaded c++ program...
13
815
by: Steve Zimmerman | last post by:
Esteemed contributors to clc: Thank you for all the responses. Experiments 2 and 3 below are identical, except that experiment 2 does not call free(), while experiment 3 does. With such a...
7
17074
by: Chris | last post by:
A general question here, what causes segmentation faults in malloc? Shouldn't malloc always gracefully fail? Take a look at the gdb core stack trace (from an HP-UX 11.11) Program terminated...
34
2750
by: Alawna | last post by:
Hi, i was reading a chapter about c pointers in "c++builder complete reference" and it is said there that malloc returns a pointer to the start of the memory allocated but i see the prototype of...
15
2002
by: Stanley S | last post by:
Hi, I'm puzzled. Why does the following cause a seg fault? Notwithstanding that I've already malloc() a certain space for "Hello". I do understand that using a fixed length array will work...
6
5958
by: mdrons | last post by:
I have a structure defined as: struct channel { int chanid; int channum; char callsign; char name; }; I then have a global variable defined as: static struct channel *chan=NULL;
6
3346
by: itsolution | last post by:
Hi folks, Could you shed some light on this issue? my program is running on Freebsd as a daemon. When user sends a request, it forks itself and lets its child process handles the request....
7
2389
by: mathieu.dutour | last post by:
Dear all, I am new to C and I have a problem with "segmentation fault" occurring unexpectedly, i.e., not immediately after a programming error. I presume I allocated wrongly before, but I can't...
22
1922
by: ravi | last post by:
Hi all, I m relatively new to C. I have few queries related to malloc(): 1. When we perform malloc(), the memory allocated dynamically comes from the heap area of the process in concern. Well,...
0
7055
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
6920
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
1
6758
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7010
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
4499
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3011
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3003
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1311
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
572
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.