473,803 Members | 3,306 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(v oid *) * (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_w eights(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*sizeo f(double));
assign_random_w eights(rows,col s);

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 3111
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(v oid *) * (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_w eights(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*sizeo f(double));
You need to check that the allocation in `malloc_weights ()' succeeded.
assign_random_w eights(rows,col s);

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(v oid *) * (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(v oid *) * (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_w eights(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*sizeo f(double));
assign_random_w eights(rows,col s);

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(v oid *) * (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)*rows ize):
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_w eights(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*sizeo f(double));
assign_random_w eights(rows,col s);

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_weight s(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_w eights(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*sizeo f(double));
if(array)
{
assign_random_w eights(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.com base.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
3506
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 dynamically allocated member variables). Anyway, I have a program that segfaults without a copy constructor but if I add an empty one, the segfault is gone. The code is ugly indeed so I don't want to post it, but, in general terms, what sort of error...
2
3087
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
3416
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 value to the td.innerHTML property. The UI is done, and I now want to post back the user's changes and update my business object in .NET. But when I postback, I can't see any of my dynamically created HTML controls in VB .NET. How do I make them...
7
7586
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 dynamically created dim c as control = me.Controls(strName) Instead I have to do this:
4
1909
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 input boxes already on the page. Anyone has any thoughts on how to solve this, your advice is much appreciated. Thanks
11
3787
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
3209
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 need to change. Thanks. #include <malloc.h> #include <string.h>
4
2716
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 multiple dynamic rows with chechboxs, input box for units of service, description of the service and each row has its own dropdown list of unit fees that apply.
49
1738
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
9700
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10546
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10292
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10068
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9121
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6841
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5627
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4275
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 we have to send another system
3
2970
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.