473,386 Members | 1,745 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,386 software developers and data experts.

Call to free() sefaults

Hello everyone. I have two questions both of which regard a homework
assignment for my "Intro to C" class. The First question that i have
is that my program segfaults when i free() memory that i malloc'd and
i'm not sure why. (without free()ing the program operates as i would
expect it to) Here is the code:

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

#define MAX 75
#define MAX_NAMES 3
#define NAME_SIZE 25

struct Name {
char name[NAME_SIZE];
struct Name *next;
};

typedef struct Name NAME;

int main (void)
{

char *entry;
int pos = 0;
int count = 0;
int inword = 0;
NAME first, middle, last, *start, *list;

/* allocate space for *entry */
entry = malloc (MAX * sizeof (char));
if (entry == NULL ) {
printf ("\n malloc() failed!\n");
exit (1);
}

/* setup list */
start = &first;
first.next = &middle;
middle.next = &last;
last.next = NULL;
list = start;
/* null first elements in case user doesn't give 3 names */
first.name[0] = '\0';
middle.name[0] = '\0';
last.name[0] = '\0';

/* input to get first, middle and last name */
printf ("Please enter your full name: ");
fgets (entry, MAX, stdin);

/* split entry up into separate name fields */
while ((*entry) && (count < MAX_NAMES)) {
if (inword) {
if (isspace (*entry)) {
list->name[pos] = '\0';
list = list->next;
inword = 0;
pos = 0;
++count;
} else
list->name[pos++] = *entry;
} else
if (!isspace (*entry)) {
list->name[pos++] = *entry;
inword = 1;
}
++entry;
}

free (entry);

/* output list structure */
list = start;
printf ("Name in list structure is: ");
while (list != NULL) {
printf ("%s ", list->name);
list = list->next;
}

printf ("\n");

return 0;
}

I'm not neccesarily looking for an "answer", maybe just a nudge in the
direction of what the problem could be, and then i could root it out.

The second question is regarding the code where i put '\0' characters
into the first elements of the arrays in the NAME structures. I wanted
to just initialize the first element in the "name" array in the NAME
structure where the stuct was declared but the compiler wouldn't
accept that. Thanks in advance for any and all comment/tips/advice.

-Chris Potter
Nov 14 '05 #1
8 1724

"Chris Potter" <ki**********@yahoo.com> wrote in message
news:6d*************************@posting.google.co m...
Hello everyone. I have two questions both of which regard a homework
assignment for my "Intro to C" class. The First question that i have
is that my program segfaults when i free() memory that i malloc'd and
i'm not sure why. (without free()ing the program operates as i would
expect it to) Here is the code:
The key here is that 'free()'s argument must be either
NULL, or the value returned from a called to 'malloc()',
'calloc()', or 'realloc()'. Your argument does not meet
these conditions (yes, I'm sure you did it inadvertently. :-))

See below.

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

#define MAX 75
#define MAX_NAMES 3
#define NAME_SIZE 25

struct Name {
char name[NAME_SIZE];
struct Name *next;
};

typedef struct Name NAME;

int main (void)
{

char *entry;
int pos = 0;
int count = 0;
int inword = 0;
NAME first, middle, last, *start, *list;

/* allocate space for *entry */
entry = malloc (MAX * sizeof (char));
if (entry == NULL ) {
printf ("\n malloc() failed!\n");
exit (1);
}
Display or otherwise record the value of 'entry' here.

/* setup list */
start = &first;
first.next = &middle;
middle.next = &last;
last.next = NULL;
list = start;
/* null first elements in case user doesn't give 3 names */
first.name[0] = '\0';
middle.name[0] = '\0';
last.name[0] = '\0';

/* input to get first, middle and last name */
printf ("Please enter your full name: ");
fgets (entry, MAX, stdin);

/* split entry up into separate name fields */
while ((*entry) && (count < MAX_NAMES)) {
if (inword) {
if (isspace (*entry)) {
list->name[pos] = '\0';
list = list->next;
inword = 0;
pos = 0;
++count;
} else
list->name[pos++] = *entry;
} else
if (!isspace (*entry)) {
list->name[pos++] = *entry;
inword = 1;
}
++entry;
}

free (entry);
Display or otherwise record the value of 'entry' here.

(Assuming the loop is not applied to an 'empty' string)
You'll notice that the value of 'entry' at this point
won't be the same as that above. (Because of your increment
(++entry) in the 'while' loop.

You can fix this problem by not incrementing 'entry' at all,
but accessing the array with a subscript which you'd increment
instead of the pointer:

(At top of function:)

size_t index = 0;

modified loop:)
while ((entry[index]) && (count < MAX_NAMES)) {
/* etc */
++index;
}

/* output list structure */
list = start;
printf ("Name in list structure is: ");
while (list != NULL) {
printf ("%s ", list->name);
list = list->next;
}

printf ("\n");

return 0;
}

I'm not neccesarily looking for an "answer", maybe just a nudge in the
direction of what the problem could be, and then i could root it out.
See above. Also, as I've alluded, don't forget that output
of particular object values in strategic locations can be
very helpful when debugging.

The second question is regarding the code where i put '\0' characters
into the first elements of the arrays in the NAME structures. I wanted
to just initialize the first element in the "name" array in the NAME
structure where the stuct was declared but the compiler wouldn't
accept that.


What statements did you use, and what exactly did the compiler say?
NAME first = {""};

/* ( first.name[0] initialized to zero, 'next' initialized to NULL) */

-Mike
Nov 14 '05 #2
>I'm not neccesarily looking for an "answer", maybe just a nudge in the
direction of what the problem could be, and then i could root it out.


You allocated some memory, you MODIFIED the pointer to it by
incrementing it, and then you freed it. Does that suggest a problem
to you?

Gordon L. Burditt
Nov 14 '05 #3
Chris Potter wrote:
printf ("\n malloc() failed!\n");
Note: Common practice is to write error messages to stderr, not stdout.
if (isspace (*entry)) {


Wrong. The ctype.h functions expect the argument to be a character
converted to the range of `unsigned char', or EOF. So use

isspace ((unsigned char) *entry)

otherwise it can break if `char' is signed and *entry is negative.

--
Hallvard
Nov 14 '05 #4
Chris Potter wrote:
Hello everyone. I have two questions both of which regard a homework
assignment for my "Intro to C" class. The First question that i have
is that my program segfaults when i free() memory that i malloc'd and
i'm not sure why.
Because that's *not* what you did. (without free()ing the program operates as i would
expect it to) Here is the code:
[... much snippage follows ...]

/* allocate space for *entry */
entry = malloc (MAX * sizeof (char));
if (entry == NULL ) {
printf ("\n malloc() failed!\n");
exit (1);
}
Here you allocated the space. But note that sizeof(char)==1 by definition,
so is pointless to include, while exit(1) has no portably defined meaning
(but exit(EXIT_FAILURE) does).
[...]
++entry;
}
Here you modify entry to point somewhere other than the beginning of the
space allocated
free (entry);
You are now trying to free with a pointer value not returned by malloc

[...] The second question is regarding the code where i put '\0' characters
into the first elements of the arrays in the NAME structures. I wanted
to just initialize the first element in the "name" array in the NAME
structure where the stuct was declared but the compiler wouldn't
accept that. Thanks in advance for any and all comment/tips/advice.


You need to show what you are trying to do. Initializing the first element
of an array (or even no elements of a static array) is sufficient, so you
are doing something other than this if your compiler complains.
--
Martin Ambuhl
Nov 14 '05 #5
In 'comp.lang.c', ki**********@yahoo.com (Chris Potter) wrote:
char *entry; entry = malloc (MAX * sizeof (char));
while ((*entry) && (count < MAX_NAMES)) {
++entry;
}

free (entry);
You have broken a sacred rule 'the value passed to free() must be value
received from malloc().

To prevent that problem, it's good practice to define the pointer 'const':

char *const entry = malloc (MAX * sizeof (char));
while ((*entry) && (count < MAX_NAMES)) {
++entry; /* Compiler error */
}

free (entry);

A fix is to use a 'mobile pointer' to read the entry (a local poinrer
initialized with the value of 'entry'), or to use an index ('entry' is an
array of char).

The second question is regarding the code where i put '\0' characters
into the first elements of the arrays in the NAME structures. I wanted
to just initialize the first element in the "name" array in the NAME
structure where the stuct was declared but the compiler wouldn't
accept that. Thanks in advance for any and all comment/tips/advice. NAME first, middle, last, *start, *list;


It's considered ugly and hard to maintain to define more that one objet per
statement. Better to stick to 'one objet, one statement' rule, and to
initialize the structure. A simple '0' is enough to force the whole structure
to 0.

NAME first = {0};
NAME middle = {0};
NAME last = {0};
NAME *start;
NAME *list;

--
-ed- em**********@noos.fr [remove YOURBRA before answering me]
The C-language FAQ: http://www.eskimo.com/~scs/C-faq/top.html
C-reference: http://www.dinkumware.com/manuals/reader.aspx?lib=cpp
FAQ de f.c.l.c : http://www.isty-info.uvsq.fr/~rumeau/fclc/
Nov 14 '05 #6
On 24 Jan 2004 18:34:48 -0800, ki**********@yahoo.com (Chris Potter)
wrote:
Hello everyone. I have two questions both of which regard a homework
assignment for my "Intro to C" class. The First question that i have
is that my program segfaults when i free() memory that i malloc'd and
i'm not sure why. (without free()ing the program operates as i would
expect it to) Here is the code:

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

#define MAX 75
#define MAX_NAMES 3
#define NAME_SIZE 25

struct Name {
char name[NAME_SIZE];
struct Name *next;
};

typedef struct Name NAME;

int main (void)
{

char *entry;
entry is uninitialized.
int pos = 0;
int count = 0;
int inword = 0;
NAME first, middle, last, *start, *list;

/* allocate space for *entry */
entry = malloc (MAX * sizeof (char));
if (entry == NULL ) {
printf ("\n malloc() failed!\n");
exit (1);
}
entry points to area obtained by malloc.

/* setup list */
start = &first;
first.next = &middle;
middle.next = &last;
last.next = NULL;
list = start;
/* null first elements in case user doesn't give 3 names */
first.name[0] = '\0';
middle.name[0] = '\0';
last.name[0] = '\0';

/* input to get first, middle and last name */
printf ("Please enter your full name: ");
fgets (entry, MAX, stdin);

/* split entry up into separate name fields */
while ((*entry) && (count < MAX_NAMES)) {
if (inword) {
if (isspace (*entry)) {
list->name[pos] = '\0';
list = list->next;
inword = 0;
pos = 0;
++count;
} else
list->name[pos++] = *entry;
} else
if (!isspace (*entry)) {
list->name[pos++] = *entry;
inword = 1;
}
++entry;
entry no longer points to start of area obtained by malloc.
}

free (entry);
Bzzt. Undefined behavior. entry does not point to start of area
obtained by malloc. The only acceptable values that may be passed to
free are:

the exact value previously returned by malloc and not yet freed
NULL

/* output list structure */
list = start;
printf ("Name in list structure is: ");
while (list != NULL) {
printf ("%s ", list->name);
list = list->next;
}

printf ("\n");

return 0;
}

I'm not neccesarily looking for an "answer", maybe just a nudge in the
direction of what the problem could be, and then i could root it out.

The second question is regarding the code where i put '\0' characters
into the first elements of the arrays in the NAME structures. I wanted
to just initialize the first element in the "name" array in the NAME
structure where the stuct was declared but the compiler wouldn't
accept that. Thanks in advance for any and all comment/tips/advice.


NAME first = {""};

This will cause first.name[0] to be set to '\0'. It will also have
the side effect of setting the remaining elements of first.name to
'\0' and first.next to NULL.
<<Remove the del for email>>
Nov 14 '05 #7
Barry Schwarz wrote:
On 24 Jan 2004 18:34:48 -0800, ki**********@yahoo.com (Chris Potter)
wrote:
int main (void)
{
char *entry; entry is uninitialized.


So what? It's first use is in:
entry = malloc (MAX * sizeof (char));


Is your observation a remnant from some rule-bound course you took?


--
Martin Ambuhl
Nov 14 '05 #8
On Sun, 25 Jan 2004 19:13:26 GMT, Martin Ambuhl
<ma*****@earthlink.net> wrote:
Barry Schwarz wrote:
On 24 Jan 2004 18:34:48 -0800, ki**********@yahoo.com (Chris Potter)
wrote:

int main (void)
{
char *entry;
entry is uninitialized.


So what? It's first use is in:
entry = malloc (MAX * sizeof (char));


Is your observation a remnant from some rule-bound course you took?


No, it was simply an attempt to show the OP the status of entry from
definition to error. Given the trivial nature of the mistake in the
original post, I refrain from making assumptions about the poster's
understanding of basic concepts.
<<Remove the del for email>>
Nov 14 '05 #9

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

Similar topics

54
by: Neo | last post by:
Hi Folks, I've a simple qestion related to dynamic memory allocation in C here is the code: #include <stdio.h> int main() {
3
by: Zheng Da | last post by:
Program received signal SIGSEGV, Segmentation fault. 0x40093343 in _int_malloc () from /lib/tls/libc.so.6 (gdb) bt #0 0x40093343 in _int_malloc () from /lib/tls/libc.so.6 #1 0x40094c54 in malloc...
24
by: Jazper | last post by:
hi i have this problem. i made a class deverted by CRootItem with implementation of IDisposable-Interface. i made a test-funktion to test my Dispose-Method.... but when set a breakpoint in my...
20
by: Cybertof | last post by:
Hello, Is there a good way to call a big time-consumming function from an ActiveX DLL (interoped) through a thread without blocking the main UI ? Here are the details : I have a class...
8
by: Berhack | last post by:
I am not too familiar with C# interop so please help me out. I need to call the following C function (in a DLL): // this creates an array of strings // LPTSTR is just char * void C_Func(LPTSTR...
5
by: Kurt Van Campenhout | last post by:
Hi, I am trying to get/set Terminal server information in the active directory on a windows 2000 domain. Since the ADSI calls for TS don't work until W2K3, I need to do it myself. I'm fairly...
24
by: John | last post by:
I know this is a very fundamental question. I am still quite confused if the program call stack stack should always grows upwards from the bottom, or the opposite, or doesn't matter?? That means...
12
by: Rahul | last post by:
Hi Everyone, I have the following code and i'm able to invoke the destructor explicitly but not the constructor. and i get a compile time error when i invoke the constructor, why is this so? ...
0
by: * Its my Pleasure * | last post by:
Call Any Phone FREE...! Send SMS FREE...! Call Anywhere in the World FREE...! Registration is Also FREE...!! Register here...http://offr.biz/HLGB7337130BVGMJPF
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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...
0
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,...
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...

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.