Hello:
I've been working on an assignment and I have hit a stumbling block pertaining to an array of pointers.
If I am correct in my assumptions, the array
should have its address passed to a function when calling it like this:
Once I am in somefunc, if I call the line of code: - free(zoo[0]);
-
zoo[0] = 0;
causes the program to crash. Specifically the error is commented out on line 261 of hw2************ ***Driver.c below. Thank you to anyone who can enlighten me on why this seemingly innoculous line is causing the program to crash.
-fauxanadu
hw2************ ***Constants.c -
/******************************************************************************
-
* PROGRAMMER : *************** *
-
* LANGUAGE : C *
-
* CLASS : CSE 1320-002, Fall 2007 *
-
* COMPILER : gcc *
-
* OPERATING SYSTEM : Unix *
-
* PLATFORM : omega *
-
* COURSE : Intermmediate Programming *
-
* ASSIGNMENT : Homework 1 *
-
* ASSIGNED : 27 September 2007 *
-
* DUE : 16 October 2007 *
-
* FILED AS : hw2***************Constants.c *
-
* FILES USED : hw2***************Constants.c *
-
* : hw2***************Driver.c *
-
* CONCEPTS : Structures, dynamic memory (de)allocation, file I/O *
-
* : Command Line Arguments *
-
* WEIGHT : 10% of Final Grade *
-
* PURPOSE : Include required system files *
-
* Define global constants *
-
* Prototype Functions *
-
*****************************************************************************/
-
// System Files
-
#include <stdlib.h>
-
#include <stdio.h>
-
-
// Constants
-
#define CMD_ARGS 2
-
#define CMD_CHAR '*'
-
#define CMD_INDEX 0
-
#define CTRL_INDEX 1
-
#define CTRL_END 'E'
-
#define CTRL_FEED 'f'
-
#define CTRL_PRCH 'p'
-
#define CTRL_TRAN 't'
-
#define DISP_FLOAT 4
-
#define DISP_INT 4
-
#define DISP_NAME 11
-
#define DISP_PREC 1
-
#define DISP_STRING 7
-
#define ERR_NONE 0
-
#define ERR_BAD_ARGS 1
-
#define ERR_MISSING_FILE 2
-
#define ERR_MALFORMED 3
-
#define FALSE 0
-
#define FILE_INDEX 1
-
#define LINE_SIZE 51
-
#define LOW_INDEX 0
-
#define NULLS '\0'
-
#define NULLP 0
-
#define STRING_LARGE 20
-
#define STRING_SMALL 10
-
#define STARTI 0
-
#define STARTT 0
-
#define TRUE 1
-
#define ZEROF 0.0
-
#define ZEROI 0
-
#define ZOO_SIZE 4
-
-
// Objects
-
struct Animal
-
{
-
char color[STRING_LARGE];
-
char name[STRING_LARGE];
-
char species[STRING_LARGE];
-
double food;
-
double water;
-
int age;
-
int id;
-
int weight;
-
};
-
-
// Function Prototypes
-
void purchase(FILE**, struct Animal*[], char[]);
-
void maintain(FILE**, struct Animal*[], char[]);
-
void report(struct Animal*[]);
-
void transfer(FILE**, struct Animal*[], char[]);
-
hw2************ ***Driver.c - /*****************************************************************************
-
* PROGRAMMER : **************** *
-
* LANGUAGE : C *
-
* CLASS : CSE 1320-002, Fall 2007 *
-
* COMPILER : gcc *
-
* OPERATING SYSTEM : Unix *
-
* PLATFORM : omega *
-
* COURSE : Intermmediate Programming *
-
* ASSIGNMENT : Homework 1 *
-
* ASSIGNED : 27 September 2007 *
-
* DUE : 16 October 2007 *
-
* FILED AS : hw2***************Driver.c *
-
* FILES USED : hw2***************Constants.c *
-
* : hw2***************Driver.c *
-
* CONCEPTS : Structures, dynamic memory (de)allocation, file I/O *
-
* : Command Line Arguments *
-
* WEIGHT : 10% of Final Grade *
-
* PURPOSE : Define Functions *
-
*****************************************************************************/
-
-
#include "hw2****************Constants.c"
-
-
int main(int argc, char* argv[])
-
{
-
//Variable Declaration
-
char lineIn[LINE_SIZE] = {NULLS};
-
FILE* input = {ZEROI};
-
struct Animal* zoo[ZOO_SIZE] = {NULLP};
-
-
// Checks that there were 2 arguments passed at the command line
-
if(argc != CMD_ARGS)
-
{
-
printf("\nError %d", ERR_BAD_ARGS);
-
printf("\nThe proper syntax is:");
-
printf("\n>executable.exe file.dat\n");
-
exit(ERR_BAD_ARGS);
-
}
-
-
// Opens the file and checks for success
-
input = fopen(argv[FILE_INDEX], "r");
-
if (!input)
-
{
-
printf("\nError %d", ERR_MISSING_FILE);
-
printf("\nThe file %s could not be opened. \n", argv[FILE_INDEX]);
-
exit(ERR_MISSING_FILE);
-
}
-
-
// Gets a line of input and determines which function to call
-
fgets(lineIn, LINE_SIZE - 1, input);
-
while(!(lineIn[CMD_INDEX] == CMD_CHAR & lineIn[CTRL_INDEX] == CTRL_END))
-
{
-
printf("\n");
-
if(lineIn[CMD_INDEX] == CMD_CHAR)
-
{
-
switch(lineIn[CTRL_INDEX])
-
{
-
case CTRL_FEED:
-
maintain(&input, zoo, lineIn);
-
break;
-
case CTRL_PRCH:
-
purchase(&input, zoo, lineIn);
-
break;
-
case CTRL_TRAN:
-
transfer(&input, zoo, lineIn);
-
break;
-
default:
-
printf("\nError %d", ERR_MALFORMED);
-
printf("\nThe input file is malformed.");
-
printf("\nPlease consult the documentation\n");
-
exit(ERR_MALFORMED);
-
}
-
}
-
report(zoo);
-
}
-
-
return ERR_NONE;
-
}
-
-
void purchase(FILE** input, struct Animal* zoo[], char lineIn[])
-
{
-
//Variable Declaration
-
int i = ZEROI;
-
char a[STRING_SMALL], b[STRING_SMALL], c[STRING_SMALL],
-
d[STRING_SMALL], e[STRING_SMALL], f[STRING_SMALL],
-
g[STRING_SMALL];
-
-
//Gets line of input
-
fgets(lineIn, LINE_SIZE - 1, *input);
-
-
//Exit Condition
-
if(lineIn[CMD_INDEX] == CMD_CHAR)
-
{
-
return;
-
}
-
-
for(i = STARTI; i < ZOO_SIZE; i++)
-
{
-
if (zoo[i] == NULLP)
-
{
-
zoo[i] = (struct Animal*)malloc(1 * sizeof(struct Animal));
-
sscanf(lineIn, "%s%s%s%s%s%s%s", a, b, c, d, e, f, g);
-
strcpy(zoo[i]->species, a);
-
strcpy(zoo[i]->name, b);
-
if(!(isdigit(c[LOW_INDEX])))
-
{
-
strcat(zoo[i]->name, " ");
-
strcat(zoo[i]->name, c);
-
zoo[i]->age = atoi(d);
-
zoo[i]->weight = atoi(e);
-
zoo[i]->id = atoi(f);
-
strcpy(zoo[i]->color, g);
-
}
-
else
-
{
-
zoo[i]->age = atoi(c);
-
zoo[i]->weight = atoi(d);
-
zoo[i]->id = atoi(e);
-
strcpy(zoo[i]->color, f);
-
}
-
zoo[i]->food = ZEROF;
-
zoo[i]->water = ZEROF;
-
printf("Purchasing: %s\n", zoo[i]->name);
-
break;
-
}
-
}
-
-
//Makes sure the for loop exited early, if not, inform user
-
if(i >= ZOO_SIZE)
-
{
-
sscanf(lineIn, "%s%s%s%s%s%s%s", a, b, c, d, e, f, g);
-
printf("Purchase failed: %s ", b);
-
if(!(isdigit(c[LOW_INDEX])))
-
{
-
printf("%s ", c);
-
}
-
printf("\n");
-
}
-
-
//Recurses and then returns
-
purchase(input, zoo, lineIn);
-
return;
-
}
-
-
void maintain(FILE** input, struct Animal* zoo[], char lineIn[])
-
{
-
//Variable Declaration
-
int i = ZEROI;
-
char a[STRING_LARGE], b[STRING_SMALL], c[STRING_SMALL], d[STRING_SMALL];
-
-
//Gets line of input
-
fgets(lineIn, LINE_SIZE - 1, *input);
-
-
//Exit Condition
-
if(lineIn[CMD_INDEX] == CMD_CHAR)
-
{
-
return;
-
}
-
-
//Separates out the desired data
-
sscanf(lineIn, "%s%s%s%s", a, b, c, d);
-
if(!(isdigit(b[LOW_INDEX])))
-
{
-
strcat(a, " ");
-
strcat(a, b);
-
}
-
-
for(i = STARTI; i < ZOO_SIZE; i++)
-
{
-
if(!(strcmp(zoo[i]->name, a)))
-
{
-
printf("Maintaining: %s\n", zoo[i]->name);
-
if(isdigit(b[LOW_INDEX]))
-
{
-
zoo[i]->food = atof(b);
-
zoo[i]->water = atof(c);
-
}
-
else
-
{
-
zoo[i]->food = atof(c);
-
zoo[i]->water = atof(d);
-
}
-
}
-
}
-
-
//Recurses and then returns
-
maintain(input, zoo, lineIn);
-
return;
-
}
-
-
void report(struct Animal* zoo[])
-
{
-
//Variable Declaration
-
static int headerPrinted = FALSE;
-
static int i = ZEROI;
-
-
//Exit condition
-
if(i >= ZOO_SIZE)
-
{
-
return;
-
}
-
-
//If the header has not been printed, prints it
-
if(headerPrinted == FALSE)
-
{
-
printf("----+------------+--------+-----+-------+--------+------+------\n");
-
printf("ID |Name |Species |Age |Weight |Color |Food |Water \n");
-
printf("----+------------+--------+-----+-------+--------+------+------\n");
-
headerPrinted = TRUE;
-
}
-
if(zoo[i])
-
{ //Prints out the current animals information
-
printf("%-*d|%-*s |%-*s |%*d | %*d |%-*s | %*.*f | %*.*f \n",
-
DISP_INT, zoo[i]->id,
-
DISP_NAME, zoo[i]->name,
-
DISP_STRING, zoo[i]->species,
-
DISP_INT, zoo[i]->age,
-
DISP_INT, zoo[i]->weight,
-
DISP_STRING, zoo[i]->color,
-
DISP_FLOAT, DISP_PREC, zoo[i]->food,
-
DISP_FLOAT, DISP_PREC, zoo[i]->water);
-
}
-
-
//Recurses and resets variables for next print
-
i++;
-
report(zoo);
-
headerPrinted = FALSE;
-
i = ZEROI;
-
return;
-
}
-
-
-
-
-
-
-
void transfer(FILE** input, struct Animal* zoo[], char lineIn[])
-
{
-
//Variable Declaration
-
int i = ZEROI;
-
char a[STRING_SMALL];
-
-
//Gets line of input
-
fgets(lineIn, LINE_SIZE - 1, *input);
-
-
//Exit Condition
-
if(lineIn[CMD_INDEX] == CMD_CHAR)
-
{
-
return;
-
}
-
-
//Separates out the desired information
-
sscanf(lineIn, "%s%s%s%s%s%s%s", a);
-
-
//Checks each element of the zoo to see if it matches
-
for(i = ZEROI; i < ZOO_SIZE; i++)
-
{
-
if(!(strcmp(zoo[i]->name, a)))
-
{
-
printf("Transfering: %s\n", zoo[i]->name);
-
free((struct Animal*)zoo[i]);
-
//zoo[i] = (struct Animal*)NULLP;
-
break;
-
}
-
}
-
-
if(i >= ZOO_SIZE)
-
{
-
printf("Transfer Failed: %s", lineIn);
-
}
-
-
//Recurses and then returns
-
transfer(input, zoo, lineIn);
-
return;
-
}
8 1318
Hi.
I've no time so I skip your assignment requirements:(
But you can see my sample code for the array of structs: - #include <stdio.h>
-
-
struct rectangle
-
{
-
int width, height;
-
};
-
-
int main()
-
{
-
struct rectangle recArray[10];
-
int i;
-
-
for(i=0; i<10; i++)
-
recArray[i].width = i;
-
-
for(i=0; i<10; i++)
-
printf("%d ", recArray[i].width);
-
-
return;
-
-
}
And the result: - charlie$ gcc structarray.c
-
charlie$ ./a.out
-
0 1 2 3 4 5 6 7 8 9 charlie$
I think this would help you to access the "properties " inside each of the struct "elements". ..
I have to use an array of dynamically allocated pointers. I can't figure out why:
zoo[0] = 0;
is causing the program to crash. zoo is defined as
struct animal* zoo[4];
and is sent to a function via
somefunc(zoo);
Once in somefunc, the assignment mentioned at the top of this post causes the program to crash.
Hi
zoo[0] is the "address to first struct element", you cannot assign an int to that address...
I would suggest you take more time reading the lecture notes for better understanding about this god damned issue...
I am doing my assignment2, which requires a linked list of linked lists...
I have read the lecture notes quite throughly and this part of the program is actually a direct copy of what the professor has in his notes. I cannot figure out why it will not work in this context.
Well, as for me I would use this:
struct rectangle recArray[10];
It means an array of struct elements, each of which could be accessed by using recArray[i].
I don't know why your pro would use struct somecClass *array[10];
I don't know how to do this job in thay way:(
RRick 463
Recognized Expert Contributor
Your problem is a one of initialization. You are trying to free something that is pointed to by an uninitialized pointer.
This code will create an array of 4 pointers to a struct animal. This does not set any of the pointer values in zoo, so using zoo[0] will access something with a bad pointer.
Later on you try to free zoo[0] and this is probably what is causing your program to blow up. If you want to free something, the pointer has to be either NULL or a valid pointer value (i.e, created by malloc,etc.).
One solution is to initialize zoo when you declare it. - struct animal * zoo[4] = { NULL, NULL, NULL, NULL};
should fix the problem.
It is actually initialized to null. (on line 28.):
28. struct Animal* zoo[ZOO_SIZE] = {NULLP};
With NULLP being equal to 0.
In the main function I can set zoo[0] = 0; just fine and it works. Once I pass the address of zoo to a function, inside that function the exact same assignment stops working. That is the problem. I need to know why as I cannot figure it out. I've been working on this problem for three nights intermittantly and it just won't work no matter what I do.
RRick 463
Recognized Expert Contributor
There are over 300 lines of code, an unknown data file, and even recursive calls. This can get complicated, very quickly.
You need to narrow down the scope of the problem and figure out the location where the problem occurs. What is needed to reproduce this problem? We also need values for zoo before and after the problem area is called.
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: dam_fool_2003 |
last post by:
Friends,
cannot we malloc a array?
So, I tried the following code:
int main(void)
{
unsigned int y={1,3,6},i,j;
for(i=0;i<3;i++)
printf("before =%d\n",y);
*y = 7; /* 1*/
|
by: fix |
last post by:
Hi all,
I feel unclear about what my code is doing, although it works but I am
not sure if there is any possible bug, please help me to verify it.
This is a trie node (just similar to tree nodes) struct, I am storing an
array of 27 pointers and a void pointer that can point to anything.
typedef struct trieNode
{
struct trieNode *children; // The children nodes
void *obj; // The object stored
} TrieNode;
|
by: gaga |
last post by:
I can't seem to get this to work:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *names;
char **np;
|
by: Alexei A. Frounze |
last post by:
Hi all,
I have a question regarding the gcc behavior (gcc version 3.3.4).
On the following test program it emits a warning:
#include <stdio.h>
int aInt2 = {0,1,2,4,9,16};
int aInt3 = {0,1,2,4,9};
|
by: Simon Morgan |
last post by:
I hope this isn't OT, I looked for a newsgroup dealing purely with
algorithms but none were to be found and seeing as I'm trying to implement
this in C I thought this would be the best place.
I have an array of structs containing data which I'd like to output
ordered based on the value of a single member. I was wondering if there is
a relatively simple way of doing this without actually modifying the
structure of the array?
I had a...
| |
by: Paminu |
last post by:
Why make an array of pointers to structs, when it is possible to just make
an array of structs?
I have this struct:
struct test {
int a;
int b;
|
by: =?Utf-8?B?U2hhcm9u?= |
last post by:
Hi Gurus,
I need to transfer a jagged array of byte by reference to unmanaged
function, The unmanaged code should changed the values of the array, and when
the unmanaged function returns I need to show the array data to the end user.
Can I do that?
How?
|
by: StevenChiasson |
last post by:
For the record, not a student, just someone attempting to learn C++. Anyway, the problem I'm having right now is the member function detAddress, of object controller.
This is more or less, your standard dynamic address book program. Adding, and listing work just fine. However, deleting, editing and viewing relies on member function retAddress. This function returns an array of pointers that are pointing to created objects. In action, all it...
|
by: Ben Bacarisse |
last post by:
candide <toto@free.frwrites:
These two statements are very different. The first one is just wrong
and I am pretty sure you did not mean to suggest that. There is no
object in C that is the same as its address.
The second one simply depends on a term that is not well-defined.
Most people consider the type to be an important part of the notion of
|
by: Adam Chapman |
last post by:
Hi,
Im trying to migrate from programming in Matlab over to C. Im trying
to make a simple function to multiply one matrix by the other. I've
realised that C can't determine the size of a 2d array, so im
inputting the dimensions of those myself.
The problem is that the output array (C=A*B) has as many rows as A and
as many columns as B. I would think of initialising C with:
|
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
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,...
|
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...
|
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...
|
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
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();...
| |
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
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...
| |