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

freeing memory allocated for char* using malloc

Dheeraj Joshi
1,123 Expert 1GB
The output what i am expecting is a segmentation fault but some output is coming.

Expand|Select|Wrap|Line Numbers
  1.                 char *str = get_time();//malloc is done in this function and returning that char*
  2.         char *str1 = "TRACE:Entering Function12";
  3.         int i = strlen(str)+strlen(str1);
  4.         char *strlog= (char*)malloc(i*sizeof(char));
  5.         strcpy(strlog,str);
  6.         strcat(strlog,str1);
  7.             free(str);
  8.         strcpy(str,"abc");
  9.         printf("%s\n",str);//this is printing "abc" as output
  10.  
Regards
Dheeraj Joshi
Aug 27 '09 #1
11 3864
JosAH
11,448 Expert 8TB
@dheerajjoshim
If you have a string of length n you need n+1 bytes to store it, i.e. one more for the string terminating '\0' character. So you have to do:

Expand|Select|Wrap|Line Numbers
  1. int i = strlen(str)+strlen(str1)+1;
  2.  
If you free a chunk of memory you can't use it anymore so don't free it if you still want to use it, free it when you're done with it altogether.

kind regards,

Jos
Aug 27 '09 #2
Dheeraj Joshi
1,123 Expert 1GB
Thanks for the info Jos... I wont get the stack trace error now..

Expand|Select|Wrap|Line Numbers
  1. int write_log(char* log_string)
  2. {
  3.         char *str = get_time();
  4.         int i = strlen(str)+strlen(log_string)+1;
  5.         char *strlog= (char*)malloc(i*sizeof(char));
  6.         strcpy(strlog,str);
  7.         strcat(strlog,log_string);
  8.         /* write to the file */
  9.         fprintf(fp,"%s\n",strlog);
  10.         free(strlog);
  11.         free(str);
  12.         strcpy(strlog,"abf");
  13.         printf("*****%s\n",strlog);
  14.         return 0;
  15. }
  16.  
Jos, i got a doubt.. I am freeying strlog and str...
But in next line when i do
Expand|Select|Wrap|Line Numbers
  1. strcpy(strlog,"abf"); 
  2. printf("*****%s\n",strlog);
  3.  
it should give a seg fault right? But it prints abf...

How i will come to know whether memory is deallocated or not?


Regards
Dheeraj Joshi
Aug 27 '09 #3
JosAH
11,448 Expert 8TB
@dheerajjoshim
It's undefined behaviour; you have freed() the memory so it isn't yours anymore. It may throw a segmentation violation in other contexts or other implementations or it may behave strangely next to you run your program; that's what undefined behaviour is all about.

To answer your last question: you don't know whether or not a piece of memory is allocated or freed, i.e. you have to go through the control flow of your program to find out.

kind regards,

Jos
Aug 27 '09 #4
Dheeraj Joshi
1,123 Expert 1GB
So.. in general Cant we find out whether a chunk of memory is free or not by doing whatever i did..?( I mean do strcpy to a freed mem location).

Regards
Dheeraj Joshi
Aug 27 '09 #5
donbock
2,426 Expert 2GB
@dheerajjoshim
It sounds like you're looking for some way to poke a chunk of dynamically allocated memory to probe whether it has been freed yet or not.

I'm not aware of any portable or reliable way to do this. A particular implementation might have an extra library containing a function to do that; but you couldn't count on that library being available if you moved your program to another platform.

The worst thing you could do would be to trigger undefined behavior and count on how your compiler appears to react.
Aug 27 '09 #6
Dheeraj Joshi
1,123 Expert 1GB
I want to make sure whether the memory is freed or not.. thats it..

Regards
Dheeraj Joshi
Aug 27 '09 #7
JosAH
11,448 Expert 8TB
@dheerajjoshim
Basically: if the memory is allocated by [m|c|re]alloc you can free it, otherwise you can't.

kind regards,

Jos
Aug 27 '09 #8
Dheeraj Joshi
1,123 Expert 1GB
I do allocate memeory using malloc....

Regards
Dheeraj Joshi
Aug 27 '09 #9
JosAH
11,448 Expert 8TB
@dheerajjoshim
Fine; you can free() it once and after you have done so you can't use the memory anymore; that's all there is to it.

kind regards,

Jos
Aug 27 '09 #10
Dheeraj Joshi
1,123 Expert 1GB
Thanks For the info guys..

I aprreciate it...

Regards
Dheeraj Joshi
Aug 27 '09 #11
weaknessforcats
9,208 Expert Mod 8TB
Actually, you can check whether memory has been freed or not. After all, the debugging tools like BoundsChecker do just that.

Here's waty those tools do.
1) they write their own malloc() and free() and use them rather than the ones provided by C.

2) Their malloc() calls the C malloc(). Then it also writes a record into a data base that has the file name and line number of their malloc() plus the number of bytes being allocated plus the address returned by the C malloc().

3) Their free() uses the argument as a key and looks up the record in the database that was put there by their malloc() and deletes that record. Then iot calls the C free(). If there is no record in that database, then you are trying to free an address that was never allocated. If the program completes and the database it no empty you have the addresses, filenames and line numbers of the memory that was never freed. These are your leaks.


On the other hand you could just but one of these tools and run your code with it. All of your memory issues will be revealed. There is no point in checking this stuff in the program you run in production.
Aug 30 '09 #12

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

Similar topics

3
by: Hassan Iqbal | last post by:
Hi, (1)if i do the memory allocation like: int **p; p= malloc(n*sizeof p); for(i=0;i<n;i++) /* i and n are integers */ p= malloc(n*sizeof p); then in that case is this command sufficient to...
12
by: f.oppedisano | last post by:
Hi, i would like to allocate two structures making only one malloc call. So i do prt=malloc(sizeof(struct1)+sizeof(struct2)); After this operation i make two pointers one to the first struct...
10
by: cijo | last post by:
Hi, My program has a pointer to a structure declared locally inside a function to which memory is allocated using malloc and reallocated later using realloc, and when I try to free the memory at...
29
by: keredil | last post by:
Hi, Will the memory allocated by malloc get released when program exits? I guess it will since when the program exits, the OS will free all the memory (global, stack, heap) used by this...
6
by: lovecreatesbeauty | last post by:
Hello experts, 1. Does C guarantee the data layout of the memory allocated by malloc function on the heap. I mean, for example, if I allocate a array of 100 elements of structure, can I always...
1
by: skg | last post by:
I am passing the address of pointer like char** from managed extension and getting the its initialized value from a C library dll. How can i free the memory from the code in Managed Extension ?...
2
by: tristan.chaplin | last post by:
I have an unmanaged dll that returns a pointer (that it allocates, I didn't allocate it with Marshal.AllocHGlobal), how do I free the memory when I'm finished with it? It doesn't seem to like me...
171
by: Raman | last post by:
Hi All, Here is a small Code, int main(void) { char *p=(char *) malloc(100); strcpy(p,"Test1234567890"); p=p+10; free(p);
6
by: Praetorian | last post by:
This is actually 2 questions: The first one: I have a function (FuncA) calling another (FuncB) with a set of parameters which also includes an int * initialized to NULL before the call. Now...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.