C malloc syntax [duplicate] - c

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);
}

Related

Arrays of struct in c [duplicate]

This question already has answers here:
C - freeing structs
(7 answers)
Closed 5 years ago.
struct a {
int a;
int b;
};
struct a* ptr = NULL;
In main
ptr = malloc(5 * sizeof(struct a ));
//assume is 5 is from user
Assign values to ptr[0].a and ptr[0].b, similarly to all 5 block
free(ptr);
Is free (ptr) enough to free all arrays of struct? Or should i free explicitly? If so, how? Thanks.
You need to free whatever is returned by any memory management function. For allocations that are nested you need to do it reverse order of the way they are allocated. (Typical example would be creation of jagged array)
void free(void *ptr);
From 7.22.3.2p2
The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.
In your case free(ptr) would be enough to free the dynamically allocated memory. If it contained some pointer variable to which we assigned address of dynamically allocated memory then you would need to free then first and then this ptr variable.

Segmentation Fault using free() in c [duplicate]

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.

Range of free on malloc returned memory [duplicate]

This question already has answers here:
How much memory would be freed if pointer is changed in C?
(3 answers)
Closed 7 years ago.
Given the following line:
int *digits = (int *) malloc(3 * sizeof(int));
Say we store the values 1, 2 and 3 in locations, digits[0], digits[1], digits[2]. As follows:
digits[0] = 1;
digits[1] = 2;
digits[2] = 3;
If the following line is called:
free(++digits);
Is the entire memory range returned by malloc freed, or just the int sized block currently pointed to by digits - at that time, digits[1]? Or is the correct way, to free the entire range by iteration, i.e:
for (i = 0; i < 3; i++)
{
free(digits[i]);
}
I am trying to understand the range of a call to free. Is the entire memory chunk returned by malloc freed, or is only a sub-portion, currently referenced by the pointer digits freed?
You must free() the exact same pointer value you get from malloc(). The entire blob of memory allocated by malloc() will be freed at once.
You can't use a pointer int the middle of the buffer returned to you by malloc() to free() it, but you must pass to free() exactly what malloc() returned you.
http://linux.die.net/man/3/malloc is pretty explicit about this.
As per rule malloc provide you with chunk of memory you demanded and return you start address of the chunk. you have to use digit to free memory as the only legal way to identify the allocated memory is pointer returned in your case it is digits

difference between allocation [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Difference between declaration and malloc
Is there a difference between these two programs?
int main(void) {
char str[80];
}
and
int main(void) {
char * str = (char*) malloc( sizeof(char) * 80 );
}
So is there a difference between using malloc and the array-like syntax? So if I need memory for 80 characters, I should use malloc and not the other possibility, right?
I'll try to answer my own question!
char str[80];
allocates 80 bytes on the stack. This will be automatically reclaimed when str goes out of scope.
char * str = (char*) malloc( sizeof(char) * 80 );
allocates 80 bytes on the heap. This memory is available until you call free.
Note that the second case can be simplified to
char * str = malloc(80);
i.e. You should not cast the return from malloc in C and sizeof(char) is guaranteed to be 1
The first is allocated on the stack, and will be free'd when the variable goes out of scope. The second on the heap, and must be free()'d explicitly.
Both can be passed as pointers.
In the first case, you allocate 80 characters on the stack, in the second case you allocate memory on the heap.
Both can be used as pointers, and passed around to functions, and both can be used with array indexing syntax as well.

Where are character arrays in dynamically allocated structs stored? [duplicate]

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.

Resources