This question already has answers here:
How to copy a char array in C?
(14 answers)
Closed 6 years ago.
I am trying to find the issue with a bit of C code that I have. The debugger says that the error occurs when I try to free the mem from a pointer:
int main(int argc, char *argv[]){
char *desc = malloc(30 * sizeof(char));
if(desc == NULL)
{
fprintf(stderr, "Error - cannot allocate memory\n");
}
desc = "Debug this program.";
printf("Description: %s\n", desc);
free(desc);//break point here
int cpid = fork();
....
You reassigned desc and then freed a pointer to a string literal, that's illegal and it causes the segmentation fault.
You apparently failed to understand what malloc() is for, malloc() requests memory from the OS and returns a pointer to valid memory that you can use in your program.
After you malloc() you can use the memory, but not all pointers need to me malloc()ed. For example, you can have pointers to string literals and they are useful too.
But you can't pass anything to free() except if it was returned by malloc()/calloc()/realloc(). A pointer to a string literal or holding the address of a variable is not such a pointer, and passing it to free() is undefined behavior.
Only use malloc() if you know that you MUST, for example to allocate a lot of memory that would overflow the stack or to allocate an unknown ammount of memory that you can calculate at runtime. Otherwise, don't.
At first you allocated dynamically memory and its address assigned to the pointer desc
char *desc = malloc(30 * sizeof(char));
Then you reassigned the pointer with the address of the first character of the string literal "Debug this program."
desc = "Debug this program.";
Thus the address of the allocated memory was lost.
Then you are trying to free the memory occupied by the string literal
free(desc);//break point here
However string literals have static storage duration and can not be freed by using standard function free.
Instead of this assignment statement
desc = "Debug this program.";
you should use standard C function strcpy as for example
strcpy( desc, "Debug this program." );
You are trying to free address of a literal string, that is illegal.
To init an mallocated string with your literal string you can use, e.g. strcpy:
strcpy(desc, "Debug this program.");
You should also exit/terminate your program in case of malloc fails.
Simply said (and read the other solutions), that memory is not yours to delete.
Related
here's the code:
can anyone explain this issue
how can i deallocate the memory of s in main
char *get(int N)
{
char *s=malloc(10*sizeof(char));
s="hello";
return s;
}
int main()
{
char *s=get(4);
printf(s);
free(s);
}
This here:
s="hello";
Doesn't write "hello" to the allocated memory. Instead, it reassigns s to point to a read-only place where "hello" is stored. The memory you allocated with malloc is leaked, and the free(s); is invalid, because you can't free that read-only memory.
If you want to copy "hello" into s, try strcpy(s,"hello"); instead.
By doing
s="hello";
you're overwriting the returned pointer by malloc() with the pointer to the first element of the string literal "hello", which is not allocated dynamically.
Next, you are passing that pointer (to a string literal) to free(), which causes the undefined behavior.
You may want to change the assignment to
strcpy(s, "hello");
Additionally, by overwriting the originally returned pointer by malloc(), you don't have a chance to deallocate the memory - so you also cause memory leak.
You have two bugs here:
You reassign the pointer s with the reference of the string literal "hello", loosing the memory allocated by malloc
You allocate not enough space for the "hello" string. You need at least 6 characters (not 4)
A variable of type char * is a pointer (memory address) to a character. In C, it is customary to implement strings as zero-terminated character arrays and to handle strings by using variables of type char * to the first element of such an array.
That way, variables of type char * do not actually contain the strings, they merely point to them.
For this reason, the line
s="hello";
does not actually copy the contents of the string, but rather only the pointer (i.e. the memory address) of the string.
If you want to copy the actual contents of the string, you must use the function strcpy instead.
By overwriting the pointer that you use to store the address of the memory allocated by malloc, you are instead passing the address of the string literal "hello" to free. This should not be done. You must instead only pass memory addresses to free that you received from malloc.
I wonder what happens inside the memory when we do something like this
char *s;
s = "Text";
s = "Another Text";
If I'm getting it right, by assigning string to char pointer memory is dynamically allocated. So according to my understanding assignment expression
s = "Text";
equals to
s = (char *) malloc(5); // "Text" + '\0'
strcpy(s, "Text");
Well, this way we can easily free memory by using
free(s);
But... After reassigning same pointer to another value, it allocates new memory segment to store that value.
s = "Text";
printf("\n(%p) s = \"%s\"", s, s);
s = "Another Text";
printf("\n(%p) s = \"%s\"", s, s);
Output:
(0x400614) s = "Text"
(0x400628) s = "Another Text"
That means that address of old value is not accessible to us any longer and we can't free that any more. Another call to free(s); will probably deallocate only last memory segment used by that pointer.
My question is: If we reassign same char pointer over and over again, does it consume more and more program memory during run-time or that garbage somehow gets automatically freed?
I hope that was enough to demonstrate my problem, couldn't think better example. If something's not clear enough please ask for additional clarification.
Your understanding is wrong. It is just the assignment and it does not allocate any memory. In your example you assign the pointer with the addresses of the string literals. String literals are created compile time and placed in the read only memory
You do now allocate any memory by assigning the pointer
It's not equal to doing a malloc. What's happening is that the string literal is stored in a read only part of memory. And it's not the assignment of a pointer that does the allocation. All string literals in a program are already allocated from start.
It might be worth mentioning that they are not strictly speaking stored in read only memory, but they might be and writing to a string literal is undefined behavior.
You cannot and should not call free on a string literal. Well, you can, but the program will likely crash.
With no optimization, compiler will reserve two distinct memory space for string literals "text1" and "text2".
If assignment lines are very consecutive as in your question and if nothing is done after the first assignment line —assuming compiling with optimization— compiler, most probably, will not allocate any space for the first string literal nor will produce any opcode for the first assignment line.
I don't understand it prints out OneExample when i allocated memory for 5.
I know it is possible to do it using strncpy
But is there a way to do it without using strncpy
It works with strncpy, but is there a way to do it without strncpy ?
void main()
{
char *a;
a=(char*)malloc(5);
a="OneExample";
printf("%s",a);
free(a);
}
It prints out OneExample
Should not it print OneE ??
Can someone explain ?
void main()
{
char *a;
a=(char*)malloc(5);
a="OneExample";
printf("%s",a);
free(a);
}
You aren't using the memory you've allocated. After allocating the memory, you override the pointer a with a pointer to a string literal, causing a memory leak. The subsequent call to free may also crash your application since you're calling free on a pointer that was not allocated with malloc.
If you want to use the space you allocated, you could copy in to it (e..g, by using strncpy).
I don't understand it prints out OneExample when i allocated memory for 5. I know it is possible to do it using strncpy But is there a way to do it without using strncpy
It works with strncpy, but is there a way to do it without strncpy ?
You can use memcpy() as an alternative.
Read about memcpy() and check this also.
Seems that you have some misunderstanding about pointers in C.
Look at this part of your code:
a=(char*)malloc(5);
a="OneExample";
printf("%s",a);
free(a);
You are allocating memory to char pointer a and then immediately pointing it to the string literal OneExample.
This is memory leak in your code because you have lost the reference of the allocated memory.
You should be aware of that the free() deallocates the space previously allocated by malloc(), calloc() or realloc() otherwise the behavior is undefined.
In your program, you are trying to free memory of string literal "OneExample" which will lead to undefined behavior.
Using memcpy(), you can do:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void) {
char *a = malloc(5);
if (a == NULL) {
fprintf (stderr, "Failed to allocate memory\n");
exit(EXIT_FAILURE);
}
memcpy (a, "OneExample", 4); // copy 4 characters to a, leaving space for null terminating character
a[4] = '\0'; // make sure to add null terminating character at the end of string
printf("%s\n",a);
free(a);
return 0;
}
Additional:
Using void as return type of main function is not as per standards. The return type of main function should be int.
Follow good programming practice, always check the malloc return.
Do not cast the malloc return.
To use malloc, you need to #include <stdlib.h> which you don't show in your code. The reason is that malloc has a prototype returning a void * and without that prototype, your compiler is going to assume it returns an int. In 64bit architectures, this is a problem, as void * is a 64bit type, and int is 32bit. This makes that the code that extracts the value returned by malloc() to take only the 32 less signifiant bits of the result, and then convert them to a pointer (as per the cast you do, that you shouldn't ---see a lot of comments about this---, and you'll avoid the error you should have got, about trying to convert a int value into a char * without a cast)
After assigning the pointer given by malloc(3) into a, you overwrite that pointer with the address of the string literal "OneExample". This makes two things:
First, you lose the pointer value given by malloc(3) and that was stored in a so you don't have it anymore, and you'll never be able to free(3) it. This is called a memory leak, and you should avoid those, as they are programming errors.
This will be making some kind of undefined behaviour in the call to free(3) that only accepts as parameter a pointer value previously returned by malloc (and this is not the actual address stored in a) Probably you got some SIGSEGV interrupt and your program crashed from this call.
When you do the assignment to a, you are just changing the pointer value that you stored in there, and not the deferred memory contents, so that's what makes sense in calling strcpy(3), because it's the only means to copy a string of characters around. Or you can copy the characters one by one, as in:
char *a = malloc(5); /* this makes a memory buffer of 5 char available through a */
int i;
for(i = 0; i < 4 /* see below */; i++)
a[i] = "OneExample"[i]; /* this is the copy of the char at pos i */
a[i] = '\0'; /* we must terminate the string if we want to print it */
the last step, is what makes it necessary to run the for loop while i < 4 and not while i < 5, as we asked malloc() for five characters, and that must include the string terminator char.
There's one standard library alternative to this, and it is:
char *a = strdup("OneExample");
which is equivalent to:
#define S "OneExample"
char *a = malloc(strlen(S) + 1); /* see the +1 to allow for the null terminator */
strcpy(a, S);
but if you want to solve your example with the truncation of the string at 5, you can do the following:
char *dup_truncated_at(const char *s, int at)
{
char *result = malloc(at + 1); /* the size we need */
memcpy(result, s, at); /* copy the first at chars to the position returned by malloc() */
result[at] = '\0'; /* and put the string terminator */
return result; /* return the pointer, that must be freed with free() */
}
and you'll be able to call it as:
char *a = dup_truncated_at("OneExample", 5);
printf("truncated %s\n", a);
free(a); /* remember, the value returned from dup_truncated_at has been obtained with a call to malloc() */
You need to be clear about what your pointer points to. First, you declare a char *a;. This is a pointer to a character.
In the line a=(char*)malloc(5);, you allocate a bit of memory with malloc and assign the location of that memory to the pointer a. (a bit colloquial, but you understand what I mean). So now a points to 5 bytes of freshly allocated memory.
Next, a="OneExample";. a gets a new value, namely the location of the string OneExample; There is now no longer a pointer available to the five bytes that were allocated. They are now orphans. a points to a string in a static context. Depending on the architecture, compiler and a lot of other things, this may be a static data space, program space or something like that. At least not part of the memory that is used for variables.
So when you do printf("%s",a);, a points to the string, and printf will print-out the string (the complete string).
When you do a free(a);, you are trying to free a part of the program, data etc space. That is, in general, not allowed. You should get an error message for that; in Linux that will be something like this:
*** Error in `./try': free(): invalid pointer: 0x000000000040081c ***
======= Backtrace: =========
/lib64/libc.so.6(+0x776f4)[0x7f915c1ca6f4]
/lib64/libc.so.6(+0x7ff4a)[0x7f915c1d2f4a]
/lib64/libc.so.6(cfree+0x4c)[0x7f915c1d6c1c]
./try[0x400740]
/lib64/libc.so.6(__libc_start_main+0xf0)[0x7f915c1737d0]
./try[0x4005c9]
======= Memory map: ========
00400000-00401000 r-xp 00000000 08:01 21763273 /home/ljm/src/try
00600000-00601000 r--p 00000000 08:01 21763273 /home/ljm/src/try
00601000-00602000 rw-p 00001000 08:01 21763273 /home/ljm/src/try
[- more lines -]
The statement a="OneExample"; does not mean “Copy the string "OneExample" into a.”
In C, a string literal like "OneExample" is an array of char that the compiler allocates for you. When used in an expression, the array automatically becomes a pointer to its first element.1
So a="OneExample" means “Set the pointer a to point to the first char in "OneExample".”
Now, a is pointing to the string, and printf of course prints it.
Then free(a) is wrong because it attempts to free the memory of "OneExample" instead of the memory provided malloc.
Footnote
1 This automatic conversion does not occur when a string literal is the operand of sizeof, is the operand of unary &, or is used to initialize an array.
the = does not copy the string only assigns the the new value to the pointer overriding the old one. You need to allocate sufficient memory to store the string and then copy it into the allocated space
#define MYTEXT "This string will be copied"
char *a = malloc(strlen(MYTEXT) + 1); //+1 because you need to store the trailing zero
strcpy(a,MYTEXT);
then you can free a when not needed anymore
Firstly here
a=(char*)malloc(5);
you have allocated 5 bytes of memory from heap and immediately
a="OneExample";
override previous dynamic memory with string literal "OneExample" base address due to that a no longer points to any dynamic memory, it causes memory leak(as no objects points that dynamic memory, it lost) here and even after that
free(a);
freeing not-dynamically allocated memory causes undefined behavior.
side note, do read this Why does malloc allocate more memory spaces than I ask for & Malloc vs custom allocator: Malloc has a lot of overhead. Why? to get some more info about malloc().
This question already has answers here:
Do I cast the result of malloc?
(29 answers)
Closed 7 years ago.
str = (char *) malloc(15);
If I do not type (char *), is there any difference in my program?
If I try to free the memory with free(str), linux freezes unexpectedly after running program.
If you program in C, it does not make a difference, the preferred syntax is actually
char *str = malloc(15);
If you were programming in C++, the return value from malloc() would not be cast implicitly as char * for storing into str. But in C++, you should not use malloc() anyway, you should write str = new char[15]; and free this memory with delete []str;.
A potential reason for free(str); to cause undefined behavior is your writing to the array pointed to by str beyond the first 15 bytes.
Use valgrind to help track down where this happens.
char *malloc(size)
unsigned size;
malloc() is used to allocate a certain number, size, of free memory and return a pointer to the beginning of it. The malloc() function is part of the dynamic allocation routines.
If an allocation request fails- that is, if there is insufficient memory to fill the request- a null pointer is returned.
You always must be very careful to make sure that you receive a valid pointer from malloc().
This is the general form of a program that will allocate 80 bytes of memory and then free them.
main()
{
char *p;
p= malloc(80);
if(!p){ printf("out of memory\n"); exit(2); }
.
.
.
free(p);
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C Array Instantiation - Stack or Heap Allocation?
When dynamically allocating a struct containing a char pointer, what happens with the actual char pointer? Where is it stored?
And once the struct is freed, is the char pointer freed along with it?
For example consider the following struct:
struct mix
{
int a;
float b;
char *s;
};
typedef struct mix mix;
And then the following code that allocates memory for it:
int main()
{
mix *ptr = (mix*)malloc(sizeof(mix));
ptr->a = 3;
ptr->b = 4.5f;
ptr->s = "Hi, there, I'm just a really long string.";
free(ptr);
return 0;
}
Is *s allocated on the stack and then freed along with *ptr? I can imagine it is indeed allocated on the stack as it's not in any way dynamically allocated (unless malloc has some functionality I'm not aware of). And I guess 'going out of scope' for *s would be at the point of freeing *ptr. Or have I got it completely wrong? :)
Thanks very much!
The space for the char* member named s is allocated on the heap, along with the rest of the members of mix after the call to malloc() (whose return value you do not need to cast). The string literal to which s is assigned is not allocated on the heap or the stack, but is part of the actual binary and has static storage duration. So this:
ptr->s = "Hi, there, I'm just a really long string.";
assigns the address of the string literal to ptr->s. If you want ptr->s to point to something other than a string literal then you need to malloc() memory for it. And for every malloc() there must be a free() so ptr->s would need to be free()d before ptr is (if ptr->s is pointing to dynamically allocate memory only).
After the call to free(), dereferencing ptr is undefined behaviour.
When you dynamically allocate mix with malloc(), you are actually allocating a block of memory to store mix structure data members, i.e.
an int (a)
a float (b)
a pointer to a char (s)
And when you call free(), you just release that block.
So, you don't allocate the string, you just allocate the string pointer.
If you want to dynamically allocate the string, you must do it explicitly (with another call to malloc()), and to avoid memory leaks you should also free the string explicitly, using free().
When you malloc for ptr, memory is allocated for all members of the struct including the pointer s which is no different to memory allocated for any other member of the struct.
You are assigning a string literal to s, so it's fine which is usually stored in the read-only section. Otherwise, you'll need to malloc for the ptr->s as well and free. Since, it's a string literal, there's no need to free s here (doing so is UB).
mix* ptr is allocated on the stack. The contents that ptr point at, a variable of type mix, is allocated dynamically on the heap, including the pointer s.
Please note that s doesn't point at anything, the pointer doesn't do anything useful. You have to set it to point at something, which could be allocated anywhere. Whatever it points to is not freed when your struct is freed. In this case you set it to point at a constant string literal allocated in ROM, so you won't need to worry about that.
Is *s allocated on the stack
*s (that is, the result of dereferencing the pointer s) isn't allocated at all. Following the malloc, ptr->s is an uninitialized pointer. It doesn't point to anything, and the expression *(ptr->s) has undefined behavior until you do ptr->s = "Hi, etc".
Once you've initialized ptr->s to point to the string literal, *(ptr->s) is the first character of the string literal, so it probably exists in some data section of the executable. Nothing is dynamically allocated other than the sizeof(mix) bytes for the struct (probably 12 bytes on a 32bit implementation).
what happens with the actual char pointer? Where is it stored?
char* is also like other members, take some bytes(take 8 byte in 64 bit machine, similar to other pointer). In your case, you are allocating memory for that structure instance in heap. so the memory for this pointer also will be allocated in same heap block which is allocated for that structure instance.
Consider this code. This gives where the char* will be:
#include <stdio.h>
typedef struct
{
int a;
float b;
char *s;
}mix;
int main()
{
printf("\n%d ,float:%d, int:%d, char*:%d", sizeof(mix), sizeof(float), sizeof(int), sizeof(char*));
return 0;
}
so size of this structure is 16 bytes. consist of 4 byte integer, 4 byte float and 8 byte char*. (In 64 bit OS, char* will be 4 bytes if OS is 32 bit.)
And once the struct is freed, is the char pointer freed along with it?
Usually the block which is pointed by char* will not be freed(If it points to a block allocated by malloc()). only the structure block will be freed. we know free() needs valid address which is returned during allocation for peaceful de-allocation. If you free without freeing that char*, it will leads to memory leak.
But your case "Hi, there, I'm just a really long string.";
the above given string is string literal which is allocated in read-only section of your program.
use gcc -S Yourprogram.c
This will generate .s file. You can look at .read_only section for this string. so even you delete your structure instance, there will be no memory leak. Because you are just pointing a address which is read-only. You are not at-all allocating memory for this string.