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

Allocation and freeing of memory for pointer to structures

2
Hi,

I have a little programm that uses an array of pointers to a structure. Everything works fine until I free up the memory.

Here is the sample code:
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>

#define MAX_SMS_LINES 15



struct SMSInfoType {
char SMSNumber[5];
char TelNumber[20];
char Time[20];
char lines[MAX_SMS_LINES][255];
};


void main()
{
int i, nrows;
struct SMSInfoType **arraySMS;


nrows=5;
arraySMS=malloc(nrows*sizeof(struct SMSInfoType *));
if(arraySMS==NULL){
printf("Memory allocation error\n");
exit(-1);
}

for(i=0;i<nrows;i++){
arraySMS[i]=malloc(sizeof(struct SMSInfoType));
if(arraySMS[i]==NULL){
printf("Memory allocation error\n");
exit(-1);
}

strcpy((*arraySMS)[i].SMSNumber,"3");
strcpy((*arraySMS)[i].TelNumber,"1234567890123456789");
strcpy((*arraySMS)[i].Time,"14:30:00");

}

for(i=0;i<nrows;i++){
printf("SMSNumber[%d]: %s TelNumber[%d]: %s Time[%d]: %s\n",i,(*arraySMS)[i].SMSNumber,i,(*arraySMS)[i].TelNumber,i,(*arraySMS)[i].Time);
}

for(i=0;i<nrows;i++){
printf("Free arraySMS[%d]\n",i);
/***************** and here it crashes !!! ***********/
free(arraySMS[i]);
}

printf("Free arraySMS\n");
free(arraySMS);
printf("Everything freed\n");
printf("end\n");

}


Has anyone an idea, what is wrong in this code and why I get an error when trying to free up the memory?

Thanks a lot
Feb 4 '08 #1
5 1873
hdanw
61
Hi,

I have a little programm that uses an array of pointers to a structure. Everything works fine until I free up the memory.


strcpy((*arraySMS)[i].SMSNumber,"3");
strcpy((*arraySMS)[i].TelNumber,"1234567890123456789");
strcpy((*arraySMS)[i].Time,"14:30:00");


Has anyone an idea, what is wrong in this code and why I get an error when trying to free up the memory?

Thanks a lot
or more importantly
this
Expand|Select|Wrap|Line Numbers
  1. (*arraySMS)[i]
  2.  
is different from this
Expand|Select|Wrap|Line Numbers
  1. (*(arraySMS[i]))
  2.  
do you see the difference?

*arraySMS is the value that arraysms is pointing to this is your table
and *(arraySMS[0]) this is your data.

Again : arraysms points to a list of pointers
and arraysms[i] is one of the pointers on that list.

This error will haunt you again. Keep in mind it is always becuase you wrote to space that was not part of your allocation. Or you are trying to free space that was not allocated.


Have you ever heard of new? and delete?

Also, there is a better way to do what you are doing.

Each time you allocate space a chunk of memory the size is dependant on the OS and memory settings, but the intire chunk is used.

if your allocation block is 4 kilobytes then you are using 4kb for each index.

Try it like this,

allocate the index like you did above,
Expand|Select|Wrap|Line Numbers
  1. struct SMSInfoType **arraySMS;
  2.  
  3.  
  4. nrows=5;
  5. arraySMS=malloc(nrows*sizeof(struct SMSInfoType *));
  6. smsdata = (... *) new structuretag[nrows];
  7.  
  8.  
But only allocate once for the data and use another temp var to hold that address.

Expand|Select|Wrap|Line Numbers
  1. SMSInfoType * arraySMSblock = malloc(nrows*sizeof(struct SMSInfoType));
  2.  
And then assign offsets into the second data block into the first allocated array

Expand|Select|Wrap|Line Numbers
  1. for( int i = 0; i < nrows; i++)
  2. {
  3.      arraySMS[i] = &arraySMSblock[i];
  4. }
  5.  
now you are only allocating one 4kb block instead of 5, and save yourself about 16kb of overhead.

and cleanup is easy
Expand|Select|Wrap|Line Numbers
  1. free(arraySMS);
  2. free(arraySMSblock);
  3.  
Actually, I think you may have to calculate the offset of each using malloc. malloc is outdated, if you use new, the offsets are calculated for you. I said MAY. I haven't used malloc since 1992;

Happy coding.

Dan -

sorry for the double post.
Feb 5 '08 #2
gpraghuram
1,275 Expert 1GB
The problem happens becos of the way you are doing strcpy
Expand|Select|Wrap|Line Numbers
  1. //Your code commented
  2.                  //strcpy((*arraySMS)[i].SMSNumber,"3");
  3.     //strcpy((*arraySMS)[i].TelNumber,"1234567890123456789");
  4.     //strcpy((*arraySMS)[i].Time,"14:30:00");
  5.  
  6. //Option 1
  7.     strcpy((*(arraySMS[i])).SMSNumber,"3");
  8.     strcpy((*(arraySMS[i])).TelNumber,"1234567890123456789");
  9.     strcpy((*(arraySMS[i])).Time,"14:30:00");
  10. //option 2
  11.     //strcpy(arraySMS[i]->SMSNumber,"3");
  12.     //strcpy(arraySMS[i]->TelNumber,"1234567890123456789");
  13.     //strcpy(arraySMS[i]->Time,"14:30:00");
  14.  
  15.  
Use either option 1 or option 2

Thanks
Raghuram
Feb 5 '08 #3
weaknessforcats
9,208 Expert Mod 8TB
for(i=0;i<nrows;i++){
arraySMS[i]=malloc(sizeof(struct SMSInfoType));
if(arraySMS[i]==NULL){
printf("Memory allocation error\n");
exit(-1);
}

strcpy((*arraySMS)[i].SMSNumber,"3");
strcpy((*arraySMS)[i].TelNumber,"1234567890123456789");
strcpy((*arraySMS)[i].Time,"14:30:00");
It looks like your strcpy() uses an i == nrows. That's outside the array.
Feb 5 '08 #4
TommyB
2
Thanks a lot for your replies:

Option 1 of gpraghuram works perfectly for me.

@weaknessforcats:
I checked by printf("%d\n",i) and the maximum i that is used in strcpy is 4. So i<nrows is always fullfilled.

@hdanw years ago a took a C++ course and I hope there was something about new and delete there. However I have to admit that due to never writting real C++ programs I completle forgot this possibility.
As I am writing in plain C I am afraid there new and delete does not exist.
Thanks a lot for enlighten me about the difference between
Expand|Select|Wrap|Line Numbers
  1.    (*arraySMS)[i]
and
Expand|Select|Wrap|Line Numbers
  1. (*(arraySMS[i]))
.
As I am writing C very rarely these counter stuff makes always knots into my brain.

Thanks a lot to all of you
Thomas
Feb 9 '08 #5
weaknessforcats
9,208 Expert Mod 8TB
@weaknessforcats:
I checked by printf("%d\n",i) and the maximum i that is used in strcpy is 4. So i<nrows is always fullfilled.
I don't think so. Here is your code:
for(i=0;i<nrows;i++){
arraySMS[i]=malloc(sizeof(struct SMSInfoType));
if(arraySMS[i]==NULL){
printf("Memory allocation error\n");
exit(-1);
}

strcpy((*arraySMS)[i].SMSNumber,"3");
strcpy((*arraySMS)[i].TelNumber,"1234567890123456789");
strcpy((*arraySMS)[i].Time,"14:30:00");
1) There is no printf() before those strcpy() calls.
2) when you leave the loop, i == nrows.

That makes the strcpy() to one element past the end of your array.
Feb 10 '08 #6

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

Similar topics

2
by: mosfets | last post by:
Hi, I'm having a little trouble figuring out the difference in terms of memory allocation between: class person_info; class A { private:
5
by: disco | last post by:
I am working on this example from a book "C Primer Plus" by Prata 4th edition - p. 672. There is no erata on this problem at the publisher's website. 1) Is it a violation of copyright laws to...
4
by: Trying_Harder | last post by:
Consider the following declaration, #include <stdio.h> #include <stdlib.h> typedef struct foo { char name; int age; }Foo;
13
by: a.zeevi | last post by:
free() multiple allocation error in C ==================================== Hi! I have written a program in C on PC with Windows 2000 in a Visual C environment. I have an error in freeing...
9
by: Sundar | last post by:
Hi, i am trying to make an application that will require registering of quite a few dlls and execute. Now one of the first bottlenecks that my mentor refused is allocation of memory or the usage...
3
by: ranjeetasharma81 | last post by:
Hi all, I have a big C-cod, in which there are lots of dynamic memory allocation used. I want to replace dynamic memroy allocation by static arrays. The following are the problems that i am...
158
by: jacob navia | last post by:
1: It is not possible to check EVERY malloc result within complex software. 2: The reasonable solution (use a garbage collector) is not possible for whatever reasons. 3: A solution like the...
11
by: vivek | last post by:
Hello, I have a pointer to a main structure which again consists of structures, enums, char, int, float and again complex structures. When i free all the contents of the main structure, it...
25
by: Andreas Eibach | last post by:
Hi again, one of the other big woes I'm having... typedef struct perBlockStru /* (structure) Long words per block */ { unsigned long *lword; } lwperBlockStru_t;
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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
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...

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.