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
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