473,785 Members | 2,863 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Allocation and freeing of memory for pointer to structures

2 New Member
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(s truct SMSInfoType *));
if(arraySMS==NU LL){
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((*arrayS MS)[i].SMSNumber,"3") ;
strcpy((*arrayS MS)[i].TelNumber,"123 456789012345678 9");
strcpy((*arrayS MS)[i].Time,"14:30:00 ");

}

for(i=0;i<nrows ;i++){
printf("SMSNumb er[%d]: %s TelNumber[%d]: %s Time[%d]: %s\n",i,(*array SMS)[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("Everyth ing 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 1889
hdanw
61 New Member
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((*arrayS MS)[i].SMSNumber,"3") ;
strcpy((*arrayS MS)[i].TelNumber,"123 456789012345678 9");
strcpy((*arrayS MS)[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 Recognized Expert Top Contributor
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 Recognized Expert Moderator Expert
for(i=0;i<nrows ;i++){
arraySMS[i]=malloc(sizeof( struct SMSInfoType));
if(arraySMS[i]==NULL){
printf("Memory allocation error\n");
exit(-1);
}

strcpy((*arrayS MS)[i].SMSNumber,"3") ;
strcpy((*arrayS MS)[i].TelNumber,"123 456789012345678 9");
strcpy((*arrayS MS)[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 New Member
Thanks a lot for your replies:

Option 1 of gpraghuram works perfectly for me.

@weaknessforcat s:
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 Recognized Expert Moderator Expert
@weaknessforcat s:
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((*arrayS MS)[i].SMSNumber,"3") ;
strcpy((*arrayS MS)[i].TelNumber,"123 456789012345678 9");
strcpy((*arrayS MS)[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
2652
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
22977
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 post example code from a book to a newsgroup? 2) The program crashes as it tries to free memory and I would like to know the best way to correct THIS section of the code. By assigning current = head, current now points to the first structure in...
4
4691
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
2484
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 multiple allocation as follows: 1. I allocated an array of pointer. 2. I Read line by line from a text file. 3. I allocated memory for the read line.
9
2465
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 of mallocs in the dlls. He tells me that for an application to run perfectly , there must be no dynamic memory in the libraries.. I am not quite impressed.. Can anyone clear out this mess please?
3
2997
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 facing: 1- From structure and dynamic memory allocation point of view, the code is very complicated. The code has various “nested structures” with a number of levels. The size of memory allocated for pointer to structure or its pointer...
158
6130
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 one proposed by Mr McLean (aborting) is not possible for software quality reasons. The program must decide
11
2013
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 takes me a lot of time (since i have to loop determining the data type and freeing it). Is there any idea to free all the contents of the structure in shortest possible time.
25
4740
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
9645
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
9480
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
10152
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
10092
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
9950
tracyyun
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...
0
5381
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
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4053
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
2880
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.