473,789 Members | 2,629 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

malloc array of structs + a little more

4 New Member
I'm having a problem with my array of structs and segmentation faults. I have this struct that represents one line of a source file:
Expand|Select|Wrap|Line Numbers
  1. struct threeTokens {
  2. int lineNumber;
  3. char* cmd;
  4. char* param;
  5. }; line;
This is the code that tries to fill the array of structs, which is a global variable called program:
Expand|Select|Wrap|Line Numbers
  1. program = malloc(numLines * sizeof(line));
  2.         while(NULL != fgets(buffer, SIZE, fp)){
  3.                 tokenPtr = strtok(buffer," ,\n");
  4.                 while(NULL != tokenPtr){
  5.                         switch(count){
  6.                         case 0: program[curLine].lineNumber = atoi(tokenPtr);
  7.                                 paramIndex += strlen(tokenPtr);
  8.                                 break;
  9.                         case 1: program[curLine].cmd = (char*)malloc(strlen(tokenPtr) * sizeof(char));
  10.                                 strcpy(program[curLine].cmd, tokenPtr);
  11.                                 paramIndex += strlen(tokenPtr);
  12.                                 break;
  13.                         default: paramLength += strlen(tokenPtr); break;
  14.                         }
  15.  
  16.                         program[curLine].param = (char*)malloc(paramLength * sizeof(char));
  17.                         for(i = 0; i < paramLength; i++){
  18.                                 program[curLine].param[i] = buffer[paramIndex + i];
  19.                         }
  20.                         tokenPtr = strtok(NULL, " \n");
  21.                 }
  22.                 curLine++;
  23.         }/*End While of buffer*/
When I try:
Expand|Select|Wrap|Line Numbers
  1. for(i = 0; i < numLines; i++){
  2.         printf("%d\t%s\t%s\n",program[i].lineNumber, program[i].cmd, program[i].param);
  3. }
I get:
Expand|Select|Wrap|Line Numbers
  1. 0       (null)
  2. 0       (null)
  3. 0       (null)
  4. 0       (null)
  5. 0       (null)
This results in a segmentation fault later on in my code which I'm sure is from me trying to access some null data. Any ideas?
Dec 7 '09 #1
8 3220
weaknessforcats
9,208 Recognized Expert Moderator Expert
Afyer you allocate the threeToken array, there are pointers (cmd and param) that are allocated but contain no address.

You need to allocate the memory those pointers point at.
Dec 7 '09 #2
kiser89
4 New Member
Isn't that what I do within my switch statement? I malloc the memory and then copy the token into the newly allocated memory, right?
Dec 7 '09 #3
weaknessforcats
9,208 Recognized Expert Moderator Expert
strcpy(program[curLine].cmd, tokenPtr);
Where have you allocated program[curLine].cmd?

strcpy will copy from tokenPtr to program[curLine].cmd until it finds a \0.

You do not own the address in program[curLine].cmd since you never allocated it and that's where your seg error comes from.

You need to allocate strlen(tokenPtr ) +1 and put that address in program[curLine].cmd before you strcpy.
Dec 7 '09 #4
kiser89
4 New Member
One line above that I have:
program[curLine].cmd = (char*)malloc(s trlen(tokenPtr) * sizeof(char));
I may need a '+1' but that doesn't explain why the entire string at program[curLine].cmd is null. At least I don't think, maybe I'm still missing what you're trying to say. But it's my understanding that line allocates the memory I need to copy tokenPtr into cmd.
Dec 7 '09 #5
kiser89
4 New Member
Anyone else? This is very frustrating :(
Dec 7 '09 #6
newb16
687 Contributor
Did you try it with '+1' ? Anyway, without reproducible example we can't help you much - you can try to step it through in debugger and see where the string that is supposed to be there corrupts, or put debug prints there for, e.g., program[0].cmd withing the loop to detect when it corrupts.
Dec 7 '09 #7
Banfa
9,065 Recognized Expert Moderator Expert
What I see is that the calculation of the token size at lines 9 and 13 using sizeof both omit to add 1 (+1) to take account of the NULL terminator so your allocated buffers are too small.

You are doing something strange with program[curLine].param in that you don't treat it like program[curLine].cmd and just allocate and copy it. I am guessing that you are string to copy everything after the first 2 tokens into it but you actually allocate and repeated copy to it causing multiple memory leaks and on cases 0 and 1through the loop quite possibly having a paramLength == 0 therefore causing invalid memory accesses by dereferencing the NULL pointer.

And finally the 2 lines that call strtok 3 and 20 use different separators which seems unlike to be correct and both include the \n character which certainly isn't correct since fgets reads a single line from the file there can be no more than a single \n of the line read. When parsing a line it is best to parse in a whitespace agnostic fashion and then strip leading and trailing white spaces from the tokens before storing them.


All the logic errors and possibilities for undefined behaviour in this code seem more than enough to me to result in the output you have.
Dec 7 '09 #8
RRick
463 Recognized Expert Contributor
I'll throw my 2 cents in and notice that count in the switch statement is never incremented. Each time you loop through you will do the same thing over and over (I assume count is initialized to 0) until you run out of tokens from strtok.

You are also doing something "weird" with the buffer by maintaining an offset paramIndex that you keep increasing. Finally, paramLength is not set until the default case, and who knows what is being copied.


What I notice in the code is that you are fighting against what is being returned by strtok. That might explain the paramIndex value. The simplest solution is to have strtok do the work for you and you control this with the delimiters passed to strtok. When strtok finds what you need, you simply copy the data from tokenPtr to your structure. There is no need to maintain an index into the buffer.
Dec 8 '09 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

36
7791
by: Bhalchandra Thatte | last post by:
I am allocating a block of memory using malloc. I want to use it to store a "header" structure followed by structs in my application. How to calculate the alignment without making any assumption about the most restrictive type on my machine? Thanks.
29
40421
by: David Hill | last post by:
Is there a difference between: /* code 1 */ struct sample test; test = malloc(sizeof(struct sample)); memset(&test, 0, sizeof(test)); /* code 2 */ struct sample test; test = calloc(1, sizeof(struct sample));
15
2185
by: Lars Tackmann | last post by:
Hi, i have the following type and struct defined typedef struct hNode { unsigned char name; unsigned long hVal; struct hNode *next; } HashNode; what i want, is to ensure that when doing:
10
9042
by: Ian Todd | last post by:
Hi, I am trying to read in a list of data from a file. Each line has a string in its first column. This is what i want to read. I could start by saying char to read in 1000 lines to the array( i think!!). But I want to use malloc. Each string is at most 50 characters long, and there may be zero to thousands of lines. How do I actually start the array? I have seen char **array etc. At first I tried char *array but I think that gives 50...
5
2073
by: Grant Austin | last post by:
What would be the correct syntax for setting up a dynamic array of structs? Suppose you have a struct declared: struct relation { FILE * binFile; unsigned int numAttrs; struct attrList * relAttrs; /* definition shown at end of post */ };
1
1788
by: mrhicks | last post by:
Hello all, I need some advice/help on a particular problem I am having. I have a basic struct called "indv_rpt_rply" that holds information for a particular device in our system which I will call INDV. The struct looks like // Some info used for the struct typedef unsigned char uint8; /* 8 bits */
5
2767
by: Bidule | last post by:
Hi, I'm trying to sort structs defined as follows: struct combinationRec { float score; char* name; }; The number of structs and the length of the "name" field are not known
1
1888
by: Kevin | last post by:
Hi all, I clearly have an issue with some pointers, structures, and memory allocation. Its probably pritty basic, but I'm a little stuck. Any help would be greatly appreciated. I'd like to instantiate an arbitrary number of arrays of arbitrary size in function_a, copy the pointers, store the data, and free any unused memory. My basic structure is as follows:
2
11945
by: hal | last post by:
Hi, I'm trying to make an array of pointers to 'TwoCounts' structs, where the size of the array is arraySize. Right now I'm just mallocing enough space for all the pointers to the structs, and mallocing space for the pointer 'countPtr' in each struct, but do I need to do anything else? Thanks. typedef struct TwoCounts { int *countPtr;
0
9666
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
10408
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...
0
10199
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
10139
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,...
1
7529
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
6769
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
5417
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...
0
5551
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4092
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

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.