473,408 Members | 1,875 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,408 software developers and data experts.

Segfault with dynamically created 2-D array

Hi all,

I'm having a problem trying to create a 2D array whose dimensions are
determined at runtime. Below my signoff is a minimal test case that
hopefully demonstrates what I'm trying to do. Unfortunately, this
segfaults. The output is the following:

$ gcc -Wall -c arrays.c
$ gcc -o arrays arrays.o
$ ./arrays
0, 0 is 0.790188
0, 1 is 0.344383
0, 2 is 0.733099
1, 0 is 0.748440
1, 1 is 0.861647
1, 2 is 0.147551
2, 0 is 0.285223
2, 1 is 0.718230
2, 2 is 0.227775
3, 0 is 0.503970
3, 1 is 0.427397
3, 2 is 0.578871
Segmentation fault

Note: This is the first pass of this problem, but the next pass will
require turning this into a 3 dimensional array with none of the
parameters known at compile time. I assume this has no bearing on the
problem, but I'm not sure.

Any critique of the code is welcome as it's been years since I've
worked with C.

Cheers,
Curtis "Ovid" Poe

#include <stdio.h>
#include <stdlib.h>

double **weights;

double ** malloc_weights(int num_rows, int rowsize)
{
int i;

/* The last element is 0, so free_weights can detect the last row
*/
weights = malloc(sizeof(void *) * (num_rows+2)); /* one extra for
sentinel */
if(weights == 0) return 0;

/* allocate the actual rows */
for(i = 0; i < num_rows; i++) {
weights[i] = malloc(rowsize);
if(weights[i] == 0) {
return 0;
}
}

/* initialize the sentinel value */
weights[num_rows+1] = 0;

return weights;
}

void assign_random_weights(int rows, int cols)
{
int i,j;

for (i = 0; i < rows+1; i++) {
for (j = 0; j < cols; j++) {
weights[i][j] = ( ((float)rand() / (float)RAND_MAX) -.05
);
printf("%d, %d is %f\n", i, j, weights[i][j]);
}
}
}

int main(void)
{
double **array;
int i,j;
int rows = 4;
int cols = 3;

array = malloc_weights(rows,cols*sizeof(double));
assign_random_weights(rows,cols);

for (i = 0; i < rows; i++)
for (j = 0; j < cols; j++)
printf("%d, %d is %f\n", i, j, weights[i][j]);
return 0;
}
Nov 13 '05 #1
4 3087
Ovid wrote:
Hi all,

I'm having a problem trying to create a 2D array whose dimensions are
determined at runtime. Below my signoff is a minimal test case that
hopefully demonstrates what I'm trying to do. Unfortunately, this
segfaults. The output is the following:

$ gcc -Wall -c arrays.c
$ gcc -o arrays arrays.o
$ ./arrays
0, 0 is 0.790188
0, 1 is 0.344383
0, 2 is 0.733099
1, 0 is 0.748440
1, 1 is 0.861647
1, 2 is 0.147551
2, 0 is 0.285223
2, 1 is 0.718230
2, 2 is 0.227775
3, 0 is 0.503970
3, 1 is 0.427397
3, 2 is 0.578871
Segmentation fault

Note: This is the first pass of this problem, but the next pass will
require turning this into a 3 dimensional array with none of the
parameters known at compile time. I assume this has no bearing on the
problem, but I'm not sure.

Any critique of the code is welcome as it's been years since I've
worked with C.

Cheers,
Curtis "Ovid" Poe

#include <stdio.h>
#include <stdlib.h>

double **weights;

double ** malloc_weights(int num_rows, int rowsize)
{
int i;

/* The last element is 0, so free_weights can detect the last row
*/
weights = malloc(sizeof(void *) * (num_rows+2)); /* one extra for
sentinel */
Well, that's two extra, but who's counting. ;-)
The following would be better:

weights = malloc(sizeof *weights * (num_rows + 1));

(Question: why sizeof(void *) in your original?)
if(weights == 0) return 0;

/* allocate the actual rows */
for(i = 0; i < num_rows; i++) {
weights[i] = malloc(rowsize);
Nope. Not enough room. Try:

weights[i] = malloc(sizeof *(weights[i]) * rowsize);
if(weights[i] == 0) {
return 0;
}
}

/* initialize the sentinel value */
weights[num_rows+1] = 0;
You really want:
weights[num_rows] = NULL;

return weights;
}

void assign_random_weights(int rows, int cols)
{
int i,j;

for (i = 0; i < rows+1; i++) {
for (j = 0; j < cols; j++) {
weights[i][j] = ( ((float)rand() / (float)RAND_MAX) -.05
);
printf("%d, %d is %f\n", i, j, weights[i][j]);
}
}
}

int main(void)
{
double **array;
int i,j;
int rows = 4;
int cols = 3;

array = malloc_weights(rows,cols*sizeof(double));
You need to check that the allocation in `malloc_weights()' succeeded.
assign_random_weights(rows,cols);

for (i = 0; i < rows; i++)
for (j = 0; j < cols; j++)
printf("%d, %d is %f\n", i, j, weights[i][j]);
return 0;
}


HTH,
--ag

--
Artie Gold -- Austin, Texas

Nov 13 '05 #2
Ovid wrote:

Hi all,

I'm having a problem trying to create a 2D array whose dimensions are
determined at runtime. [...]

#include <stdio.h>
#include <stdlib.h>

double **weights;

double ** malloc_weights(int num_rows, int rowsize)
{
int i;

/* The last element is 0, so free_weights can detect the last row
*/
weights = malloc(sizeof(void *) * (num_rows+2)); /* one extra for
sentinel */
First mistake (which you may be getting away with).
`weights' is a `double**', that is, a pointer to a `double*'.
A `double*' is not a `void*', and may possibly have a
different size (although on many machines their sizes are
identical, which is why you may not have been hurt -- yet).
You should write `sizeof(double*)' instead of `sizeof(void*)'.
Even better, write `sizeof *weights' and let the compiler
figure it out.
if(weights == 0) return 0;

/* allocate the actual rows */
for(i = 0; i < num_rows; i++) {
weights[i] = malloc(rowsize);


Second mistake (which is almost certainly biting you).
`weights[i]' is a `double*', a pointer to `double'. It is
almost certainly the case that `sizeof(double)' is greater
than one, yet you're allocating only one byte per element
instead of `sizeof(double)' bytes per element. Remember
how you multipled by a `sizeof' (albeit the wrong one) in
the previous allocation? You must also do so here:

weights[i] = malloc(rowsize * sizeof *weights[i]);

I didn't study the rest of your program for further
errors, but these two are already enough to doom you. Fix
them first, and see what happens.

--
Er*********@sun.com
Nov 13 '05 #3
On 19 Sep 2003 09:21:42 -0700, po**@yahoo.com (Ovid) wrote:
Hi all,

I'm having a problem trying to create a 2D array whose dimensions are
determined at runtime. Below my signoff is a minimal test case that
hopefully demonstrates what I'm trying to do. Unfortunately, this
segfaults. The output is the following: snip sample output#include <stdio.h>
#include <stdlib.h>

double **weights;

double ** malloc_weights(int num_rows, int rowsize)
As is evident from the previous responses, your practice of including
sizeof(double) in the calculation of rowsize is sufficiently uncommon
to confuse people. That alone is a reasonable argument for not doing
so.

However, it is not the cause of your problem. Keep reading.
{
int i;

/* The last element is 0, so free_weights can detect the last row
*/
weights = malloc(sizeof(void *) * (num_rows+2)); /* one extra for
sentinel */
Here you allocate space for 6 pointers. Others have pointed out that
sizeof(void*) is not what you wanted. Since sizeof(double*) usually
has the same value, it will normally not lead to the segfault you
experience.
if(weights == 0) return 0;

/* allocate the actual rows */
for(i = 0; i < num_rows; i++) {
weights[i] = malloc(rowsize);
if(weights[i] == 0) {
return 0;
}
}
Here you have initialized four of the six pointers, specifically
weights[0], [1], [2], and [3].

/* initialize the sentinel value */
weights[num_rows+1] = 0;
Here you initialize a fifth pointer, weights[5]. Note that the sixth
pointer, weights[4], is never initialized.

return weights;
}

void assign_random_weights(int rows, int cols)
{
int i,j;

for (i = 0; i < rows+1; i++) {
Here you try to process five rows, 0, 1, 2, 3, and 4.
for (j = 0; j < cols; j++) {
weights[i][j] = ( ((float)rand() / (float)RAND_MAX) -.05
As soon as i becomes 4, this statement invokes undefined behavior
since weights[4] is still uninitialized. This is what causes your
segfault.
);
printf("%d, %d is %f\n", i, j, weights[i][j]);
}
}
}

int main(void)
{
double **array;
int i,j;
int rows = 4;
int cols = 3;

array = malloc_weights(rows,cols*sizeof(double));
assign_random_weights(rows,cols);

for (i = 0; i < rows; i++)
for (j = 0; j < cols; j++)
printf("%d, %d is %f\n", i, j, weights[i][j]);
return 0;
}


<<Remove the del for email>>
Nov 13 '05 #4


Ovid wrote:
Hi all,

I'm having a problem trying to create a 2D array whose dimensions are
determined at runtime. Below my signoff is a minimal test case that
hopefully demonstrates what I'm trying to do. Unfortunately, this
segfaults. The output is the following:

$ gcc -Wall -c arrays.c
$ gcc -o arrays arrays.o
$ ./arrays
0, 0 is 0.790188
0, 1 is 0.344383
0, 2 is 0.733099
1, 0 is 0.748440
1, 1 is 0.861647
1, 2 is 0.147551
2, 0 is 0.285223
2, 1 is 0.718230
2, 2 is 0.227775
3, 0 is 0.503970
3, 1 is 0.427397
3, 2 is 0.578871
Segmentation fault

Note: This is the first pass of this problem, but the next pass will
require turning this into a 3 dimensional array with none of the
parameters known at compile time. I assume this has no bearing on the
problem, but I'm not sure.

Any critique of the code is welcome as it's been years since I've
worked with C.

Not a bad start but you have several problems that need to
be corrected. The most serious errors are that you are not
allocating enough space and you have a serious memory leak
should the allocations fail. Why return the global variable?
Actually, why do you declare the global variable weights?
Cheers,
Curtis "Ovid" Poe

#include <stdio.h>
#include <stdlib.h>

double **weights;

double ** malloc_weights(int num_rows, int rowsize)
{
int i;
weights = malloc(sizeof(void *) * (num_rows+2)); /* one extra for
sentinel */
weights = malloc((sizeof *weights)*(num_rows+1));
if(weights == 0) return 0;

/* allocate the actual rows */
for(i = 0; i < num_rows; i++) {
weights[i] = malloc(rowsize);
weights[i] = malloc((sizeof **weights)*rowsize):
if(weights[i] == 0) {
TODO: To prevent a memory leak that could occur, free up all
previously allocated space if an allocation error occurs here.

return 0; }
}

/* initialize the sentinel value */
weights[num_rows+1] = 0;

return weights;
}

void assign_random_weights(int rows, int cols)
{
int i,j;

for (i = 0; i < rows+1; i++) {
for (j = 0; j < cols; j++) {
weights[i][j] = ( ((float)rand() / (float)RAND_MAX) -.05
);
printf("%d, %d is %f\n", i, j, weights[i][j]);
}
}
}

int main(void)
{
double **array;
int i,j;
int rows = 4;
int cols = 3;

array = malloc_weights(rows,cols*sizeof(double));
assign_random_weights(rows,cols);

for (i = 0; i < rows; i++)
for (j = 0; j < cols; j++)
printf("%d, %d is %f\n", i, j, weights[i][j]);
return 0;
}


corrected:

#include <stdio.h>
#include <stdlib.h>

double **malloc_weights(int num_rows, int rowsize)
{
int i;
double **dd;

dd = malloc((sizeof *dd)*(num_rows+1));/* extra sentinel value*/
if(dd == NULL) return NULL;
/* allocate the actual rows */
for(i = 0; i < num_rows; i++)
{
dd[i] = malloc((sizeof **dd) * rowsize);
if(dd[i] == NULL)
{
for(i-- ; i >= 0; i--) free(dd[i]);
free(dd);
return NULL;
}
}
/* initialize the sentinel value */
dd[num_rows] = NULL;
return dd;
}

void assign_random_weights(double **array, int rows, int cols)
{
int i,j;

for (i = 0; i < rows; i++)
for (j = 0; j < cols; j++)
array[i][j] = (((float)rand()/(float)RAND_MAX)-.05);
}

int main(void)
{
double **array;
int i,j;
int rows = 4;
int cols = 3;

array = malloc_weights(rows,cols*sizeof(double));
if(array)
{
assign_random_weights(array, rows,cols);
for (i = 0; i < rows; i++)
for (j = 0; j < cols; j++)
printf("%d, %d is %f\n", i, j, array[i][j]);

/* free the array */
for(i = 0;i < rows;i++) free(array[i]);
free(array);
}
return 0;
}

--
Al Bowers
Tampa, Fl USA
mailto: xa*@abowers.combase.com (remove the x)
http://www.geocities.com/abowers822/

Nov 13 '05 #5

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

Similar topics

4
by: William Payne | last post by:
Hello, I was under the impression that if I made a class Foo and if I didn't specify a copy constructor I would get one anyway that simply assigns the member variables (and that won't work for...
2
by: vlindos | last post by:
I have this code <code> #include <stdio.h> #include <stdlib.h> #include <mysql/mysql.h> char locale_loaded; int i18n_num;
1
by: Marcus | last post by:
I have a problem maybe one of you could help me with. I've created a data entry screen with lots of dynamically-created client-side controls. I create HTML texboxes client-side by assigning a...
7
by: mef526 | last post by:
I would like to reference a dynamically created control and I know the name. I would like to use the following: Dim strName as String = "txtControl1" ' This is the ".Name" used when textbox was...
4
by: Stone Chen | last post by:
Hello, I have form that uses javascript createElement to add additional input fields to it. However, my validating script will not process new input fields because it can only find the named...
11
by: skumar434 | last post by:
Hi everybody, I am faceing problem while assigning the memory dynamically to a array of structures . Suppose I have a structure typedef struct hom_id{ int32_t nod_de; int32_t hom_id;
8
by: nobrow | last post by:
Okay ... Im out of practice. Is it not possible to have a 2D array where each column is of a different type, say an int and a struct*? The following seg faults for me and I cant figure out what I...
4
by: assgar | last post by:
Hi I am stuck on a problem. I use 3 scripts(form, function and process). Development on win2003 server. Final server will be linux Apache,Mysql and PHP is being used. The form displays...
49
by: comp.lang.php | last post by:
/** * Class for grayscaling image * * @author Phil Powell * @version 1.2.1 * @package IMAGE_CATALOG::IMAGE */ class ImageGrayscaleGenerator extends ImageResizeComponents { /
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
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
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
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.