473,714 Members | 5,154 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

malloc for members of a structure and a segmentation fault

I am pretty new to C and doing my first project in C. I actually read
almost the entire FAQ, but can't seem to figure out this problem.

I have a structure. I have a list of these structures. Inside each
structure, I have two members: a list of strings, and a string.

I have made a sample program below that exhibits the error I am
having. I also read about Valgrind, and used it to tell me where I
was getting the segmentation fault, which is really helpful. The
Valgrind output is below my sample code.

At line 72 (it is labeled below), I use an unitialized value and then,
I try to write to it. I am not sure what I am doing wrong, because I
think I am initializing the value inside my "initialize " routine. Can
anyone help me figure out where I am going wrong.

/*************** *************** **** START SAMPLE CODE
*************** *************** ********/

#include <stdlib.h>
#include <alloca.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#define MAXSTRINGS 50
#define MAXSTRING 80
#define MAXSAMPLES 50

/* this is my sample structure. its members are a character poitner,
and a pointer to a character pointer */

struct sample {
char *string; /*substitute will fill in full path_name */
char **stringlist; /*list of arguments to send to execve */
};

int main (void) {

/* function declarations */
struct sample **initialize(st ruct sample **samplist);
void test (struct sample **samplist);

/* neener is a pointer to a pointer of type sample* */
struct sample **neener;

neener = initialize(neen er);
test (neener);
}

struct sample **initialize (struct sample **samplist) {

struct sample *sp;
int i, j;

/* allocate enough space for 50 pointers to sample structures */
samplist = (struct sample **) malloc (MAXSAMPLES * sizeof(struct
sample *));

/* set sp to the the first pointer allocated to samplist */
sp = *samplist;

/* for each of samplist's pointers to sample structures, */
for (i = 0; i < MAXSAMPLES; ++i) {

/* allocate enough space for one pointer to the sample structure
*/
sp = (struct sample *) malloc (sizeof (struct sample));

/* allocate enough space of the for a string */
sp->string = (char *) malloc (MAXSTRING * sizeof (char));

/* allocate enough pointers for the stringlist member's pointer*/
sp->stringlist = (char **) malloc (MAXSTRINGS * sizeof (char *));
/* and for each of stringlists pointers, allocate enough space for
a string*/
for (j = 0; j < MAXSTRINGS; ++j)
*(sp->stringlist + j) = (char *) malloc (MAXSTRING *
sizeof(char));

/* increment sp so it points to samplist's next allocated pointer
*/
++sp;
}
return samplist;
}

void test (struct sample **samplist) {

struct sample *sp;
char *string;
sp = *samplist;
string = "Testing 1 2 3";

*(sp->stringlist + 0) = strcpy(*(sp->stringlist + 0), string); /*
line 72 */
/* segmentation fault */
}
/*************** *************** **** END SAMPLE CODE
*************** *************** ********/

/*************** *************** **** START VALGRIND OUTPUT
*************** *************** */

==18077== Use of uninitialised value of size 4
==18077== at 0x8048494: test (test.c:72)
==18077== by 0x80483CD: main (test.c:30)
==18077==
==18077== Invalid read of size 4
==18077== at 0x8048494: test (test.c:72)
==18077== by 0x80483CD: main (test.c:30)
==18077== Address 0x4 is not stack'd, malloc'd or (recently) free'd
==18077==
==18077== Process terminating with default action of signal 11
(SIGSEGV)
==18077== Access not within mapped region at address 0x4
==18077== at 0x8048494: test (test.c:72)
==18077== by 0x80483CD: main (test.c:30)
==18077==
==18077== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 11 from
1)
==18077== malloc/free: in use at exit: 214,600 bytes in 2,651 blocks.
==18077== malloc/free: 2,651 allocs, 0 frees, 214,600 bytes allocated.
==18077== For counts of detected errors, rerun with: -v
==18077== searching for pointers to 2,651 not-freed blocks.
==18077== checked 60,224 bytes.

/*************** *************** **** END VALGRIND OUTPUT
*************** *************** */
Sep 15 '08 #1
25 3369
On Sep 15, 11:44 pm, jbholman <jbhol...@gmail .comwrote:
I am pretty new to C and doing my first project in C. I actually read
almost the entire FAQ, but can't seem to figure out this problem.
<snip>
#include <stdlib.h>
#include <alloca.h>
Your code fails here. <alloca.his not a standard header defined by
the language.

Post to an appropriate newsgroup, if any, or simply read your
implementations documentation, if any.
Sep 15 '08 #2
On Sep 15, 3:47*pm, vipps...@gmail. com wrote:
Sorry about this. I removed the the #include <alloca.hand
recompiled. I used gcc 4.2.3. I still get the same error with
identical results from Valgrind. Sorry again about that.
On Sep 15, 11:44 pm, jbholman <jbhol...@gmail .comwrote:
I am pretty new to C and doing my first project in C. *I actually read
almost the entire FAQ, but can't seem to figure out this problem.

<snip>
#include <stdlib.h>
#include <alloca.h>

Your code fails here. <alloca.his not a standard header defined by
the language.

Post to an appropriate newsgroup, if any, or simply read your
implementations documentation, if any.
Sep 15 '08 #3
On Sep 15, 11:55 pm, jbholman <jbhol...@gmail .comwrote:
Sorry about this. I removed the the #include <alloca.hand
recompiled. I used gcc 4.2.3. I still get the same error with
identical results from Valgrind. Sorry again about that.
<snip top post>

Please don't top post.
See
<http://www.catb.org/jargon/html/T/top-post.html>
<http://www.caliburn.nl/topposting.html >

Now, the next error is when you include <unistd.hwhic h is also not a
standard header.
Removing all those things that are not standard C, and you'll end up
with a program that doesn't quite do what you want. Instead of doing
that, post in an appropriate newsgroup.
(I don't know where exactly to direct you, but perhaps
<news:comp.unix .programmerwoul d be appropriate)
Sep 15 '08 #4
In article <4e************ *************** *******@k37g200 0hsf.googlegrou ps.com>,
<vi******@gmail .comwrote:
>Please don't top post.
Please do top post, if you feel it makes your article clearer.

-- Richard
--
Please remember to mention me / in tapes you leave behind.
Sep 15 '08 #5
Please don't top post.

I also apologize for top posting. I removed the <unistd.hhead er as
well. Now my only headers are <stdlib.h>, <stdio.h>, and <string.h>.
I recompiled using gcc. I then got the same error.

Sep 15 '08 #6
Richard Tobin wrote:
In article
<4e************ *************** *******@k37g200 0hsf.googlegrou ps.com>,
<vi******@gmail .comwrote:
Please don't top post.

Please do top post, if you feel it makes your article clearer.
No, don't. There was nothing clearer about that.


Brian
Sep 15 '08 #7
On 15 Sep, 21:44, jbholman <jbhol...@gmail .comwrote:
#include <stdlib.h>
#include <alloca.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#define MAXSTRINGS 50
#define MAXSTRING 80
#define MAXSAMPLES 50

/* this is my sample structure. *its members are a character poitner,
* *and a pointer to a character pointer */

struct sample {
* char *string; */*substitute will fill in full path_name */
* char **stringlist; * /*list of arguments to send to execve */

};

int main (void) {

* /* function declarations */
* struct sample **initialize(st ruct sample **samplist);
* void test (struct sample **samplist);

* /* neener is a pointer to a pointer of type sample* * */
* struct sample **neener;

* neener = initialize(neen er);
This is probably not your problem, but it may show you are confused
about how pointers work. neener doesn't have a specific value before
this line is executed, so there's no point in sending its old value -
which could be anything - to the initialize function.
* test (neener);

}

struct sample **initialize (struct sample **samplist) {

* struct sample *sp;
* int i, j;
Similarly to what I said above - you don't need a value for samplist
at this point. In fact the value it does have is about to be
overwritten.
* /* allocate enough space for 50 pointers to sample structures */
* samplist = (struct sample **) malloc (MAXSAMPLES * sizeof(struct
sample *));
Just to be clear - samplist points to a space which is big enough for
50 pointers to samples. None of these pointers points anywhere yet,
and you haven't yet allocated any space for the samples themselves.
* /* set sp to the the first pointer allocated to samplist * */
* sp = *samplist;
This line makes no sense. As I just said, samplist has space for 50
pointers, but none of them point anywhere yet. So you don't want to
set sp to be the same as the first pointer. Besides, you're about to
overwrite the value of sp with something else...
* /* for each of samplist's pointers to sample structures, */
* for (i = 0; i < MAXSAMPLES; ++i) {

* * /* allocate enough space for one pointer to the sample structure
*/
* * sp = (struct sample *) malloc (sizeof (struct sample));

* * /* allocate enough space of the for a string */
* * sp->string = (char *) malloc (MAXSTRING * sizeof (char));

* * /* allocate enough pointers for the stringlist member's pointer*/
* * sp->stringlist = (char **) malloc (MAXSTRINGS * sizeof (char *));
* * /* and for each of stringlists pointers, allocate enough space for
a string*/
* * for (j = 0; j < MAXSTRINGS; ++j)
* * * *(sp->stringlist + j) = (char *) malloc (MAXSTRING *
sizeof(char));
I think you're OK so far...
* * /* increment sp so it points to samplist's next allocated pointer
*/
* * ++sp;
No! This is where you go wrong. sp points to a sample which you
allocated space for, and which you have filled up. What you need at
this point is:

samplist[i] = sp;

to store the address of this sample in your samplist list.

Remember, sp points to a space big enough for just one sample, because
that's what you said when you malloc'ed it. sp++ will make sp point at
the unallocated space just after it. There's no reason why this space
should be free for you to do things with. And if you don't tell
samplist where your samples are, you'll never find them again.
* }
* return samplist;

}
Hope that helps.
Paul.
Sep 15 '08 #8
>I am pretty new to C and doing my first project in C. I actually read
>almost the entire FAQ, but can't seem to figure out this problem.

I have a structure. I have a list of these structures. Inside each
structure, I have two members: a list of strings, and a string.

I have made a sample program below that exhibits the error I am
having. I also read about Valgrind, and used it to tell me where I
was getting the segmentation fault, which is really helpful. The
Valgrind output is below my sample code.

At line 72 (it is labeled below), I use an unitialized value and then,
I try to write to it. I am not sure what I am doing wrong, because I
think I am initializing the value inside my "initialize " routine. Can
anyone help me figure out where I am going wrong.

/*************** *************** **** START SAMPLE CODE
************** *************** *********/

#include <stdlib.h>
#include <alloca.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#define MAXSTRINGS 50
#define MAXSTRING 80
#define MAXSAMPLES 50

/* this is my sample structure. its members are a character poitner,
and a pointer to a character pointer */

struct sample {
char *string; /*substitute will fill in full path_name */
char **stringlist; /*list of arguments to send to execve */
};

int main (void) {

/* function declarations */
struct sample **initialize(st ruct sample **samplist);
void test (struct sample **samplist);

/* neener is a pointer to a pointer of type sample* */
struct sample **neener;

neener = initialize(neen er);
You are passing an uninitialized pointer to initialize().
test (neener);
}

struct sample **initialize (struct sample **samplist) {

struct sample *sp;
int i, j;

/* allocate enough space for 50 pointers to sample structures */
samplist = (struct sample **) malloc (MAXSAMPLES * sizeof(struct
sample *));
Since you never use the value of samplist passed in to initialize()
before overwriting it, why pass in this value at all?
/* set sp to the the first pointer allocated to samplist */
sp = *samplist;
*samplist is memory you just allocated with malloc(). It is
uninitialized. Why are you accessing this? Also, it doesn't appear
that you ever use the value of sp before assigning to it again.
Are you using two different variables, both called 'sp', for
different purposes here?
/* for each of samplist's pointers to sample structures, */
for (i = 0; i < MAXSAMPLES; ++i) {

/* allocate enough space for one pointer to the sample structure
No, you are allocating enough space for one *STRUCTURE*, not a
pointer to it.
>*/
sp = (struct sample *) malloc (sizeof (struct sample));

/* allocate enough space of the for a string */
sp->string = (char *) malloc (MAXSTRING * sizeof (char));

/* allocate enough pointers for the stringlist member's pointer*/
sp->stringlist = (char **) malloc (MAXSTRINGS * sizeof (char *));
/* and for each of stringlists pointers, allocate enough space for
a string*/
for (j = 0; j < MAXSTRINGS; ++j)
*(sp->stringlist + j) = (char *) malloc (MAXSTRING *
sizeof(char) );

/* increment sp so it points to samplist's next allocated pointer
*/
++sp;
No, you stomp over this the next iteration of the loop.
}
return samplist;
}

void test (struct sample **samplist) {

struct sample *sp;
char *string;
sp = *samplist;
string = "Testing 1 2 3";

*(sp->stringlist + 0) = strcpy(*(sp->stringlist + 0), string); /*
line 72 */
/* segmentation fault */
}
/*************** *************** **** END SAMPLE CODE
************** *************** *********/

/*************** *************** **** START VALGRIND OUTPUT
************** *************** **/

==18077== Use of uninitialised value of size 4
==18077== at 0x8048494: test (test.c:72)
==18077== by 0x80483CD: main (test.c:30)
==18077==
==18077== Invalid read of size 4
==18077== at 0x8048494: test (test.c:72)
==18077== by 0x80483CD: main (test.c:30)
==18077== Address 0x4 is not stack'd, malloc'd or (recently) free'd
==18077==
==18077== Process terminating with default action of signal 11
(SIGSEGV)
==18077== Access not within mapped region at address 0x4
==18077== at 0x8048494: test (test.c:72)
==18077== by 0x80483CD: main (test.c:30)
==18077==
==18077== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 11 from
1)
==18077== malloc/free: in use at exit: 214,600 bytes in 2,651 blocks.
==18077== malloc/free: 2,651 allocs, 0 frees, 214,600 bytes allocated.
==18077== For counts of detected errors, rerun with: -v
==18077== searching for pointers to 2,651 not-freed blocks.
==18077== checked 60,224 bytes.

/*************** *************** **** END VALGRIND OUTPUT
************** *************** **/

Sep 15 '08 #9
On Sep 16, 12:12 am, jbholman <jbhol...@gmail .comwrote:
Please don't top post.

I also apologize for top posting. I removed the <unistd.hhead er as
well. Now my only headers are <stdlib.h>, <stdio.h>, and <string.h>.
I recompiled using gcc. I then got the same error.

Are you the same person I adviced some time ago not to top-post and he
quoted me with the attributes deleted?
Or it's a common thing among top-posters to delete attributes in their
struggle to keep the reply at the bottom?
Regardless, please leave the attributes untouched.
Sep 15 '08 #10

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

Similar topics

9
29700
by: Bin Lu | last post by:
I keep getting this malloc problem when my program tries to allocate memory for some pointer. The statement is like: rsv_cache = (rsvcache *) malloc (sizeof(rsvcache)); It goes through the function with this statement several times and seems that it has successfully allocated the memory. and then at some iteration, it just gets this segmentation fault. The gdb gives the following message:
13
7288
by: John | last post by:
In the course of an assignment, I learned the hard way that I shouldn't try to free a malloc'd member of a malloc'd structure after having freed that structure (i.e., free( structure ); free( structure->bufferspace ) ). My question is, if I free just the structure, will the (e.g.) bufferspace be freed implicitly, or do I have to (as I currently am) free the members first? Thanks. -cjl
7
3354
by: Alexandre | last post by:
Hello, Maybe it's a little OT, but the fact is that I don't necessarly want to know "how to correct?", but "why it happens?" I have a program who "segment fault" (ok, that's "normal"... ;-) but this time, it's not my code who "segment fault" but it's in the call of malloc/mallopt I've got:
3
11435
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 () from /lib/tls/libc.so.6 It's really strange; I just call malloc() like "tmp=malloc(size);" the system gives me Segmentation fault I want to write a code to do like a dynamic array, and the code is as
6
4777
by: I_have_nothing | last post by:
Hi! I am new in C. I try to use dynamical allocation fuction malloc( ) and realloc( ). I found something strange. After several calling realloc( ), the malloc( ) will give me a Segmentation fault. If I just call realloc( ) once before calling malloc( ), it is OK. Why? I am trying to read some double-typed items from infile and save them
13
1478
by: Thomas Barth | last post by:
Hi, I would like to create a file index like updatedb on Linux does as a part of my program, but I dont know how long the filenames could be. Therefore I want to use malloc to keep the size of the filenames flexible. I would expect an segmentation fault with the following sourcecode, when invoking strcat or sprintf to assign the first value to szFile because of missing space. function with recursion...
68
15691
by: James Dow Allen | last post by:
The gcc compiler treats malloc() specially! I have no particular question, but it might be fun to hear from anyone who knows about gcc's special behavior. Some may find this post interesting; some may find it off-topic or confusing. Disclaimers at end. The code samples are intended to be nearly minimal demonstrations. They are *not* related to any actual application code.
40
540
by: ramu | last post by:
Hi, what happens when i run the below code? main() { int *p; while(1) p= (int *)malloc(1000); } Do i get segmentation fault?
22
2920
by: friend.05 | last post by:
typedef struct { int a; int b; int c; } ABC; typedef struct { int d;
0
8808
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
8712
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,...
0
9179
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 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...
1
9077
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
7954
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...
1
6638
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 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...
0
5959
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();...
1
3160
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
2113
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.