What does "pointer being freed was not allocated" mean exactly? - c

I have trouble with a program where im trying to copy a string to a structs string variable in c. After copying the string im trying to free the temporary string variable which is copied to the structs string variable. But when i try to free the string the program turns on me and says that "pointer being freed was not allocated". I don't understand exactly what is going on.
char str[]=" "; //temporary string to copy to structs string
str[3]=s; //putting a char s in middle
strcpy(matrix[i-1][j].c, str); //copying the string
free(str); //freeing str that now is useless when copied

Only pointers returned by calls to malloc(), realloc() or calloc() can be passed to free() (dynamically allocated memory on the heap). From section 7.20.3.2 The free function of C99 standard:
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 the calloc, malloc, or realloc function, or if the space has been deallocated by a call to free or realloc,
the behavior is undefined.
In the posted code, str is not dynamically allocated but is allocated on the stack and is automatically released when it goes out of scope and does not need to be free()d.

Be careful. This code shows confusion about two things:
The difference between stack and heap memory
The operation of strcpy
Point 1
This has already been answered in a way, but I'll expand a little:
The heap is where dynamic memory is given to your process. When you call malloc (and related functions), memory is returned on the heap. You must free this memory when you are done with it.
The stack is part of your process's running state. It is where ordinary variables are stored. When you call a function, its variables are pushed onto the stack and popped back off automatically when the function exits. Your str variable is an example of something that is on the stack.
Point 2
I'd like to know what that c member of your matrix array is. If it is a pointer, then you might be confused about what strcpy does. The function only copies bytes of a string from one part of memory to another. So the memory has to be available.
If c is a char array (with sufficient number of elements to hold the string), this is okay. But if c is a pointer, you must have allocated memory for it already if you want to use strcpy. There is an alternative function strdup which allocates enough memory for a string, copies it, and returns a pointer. You are responsible for freeing that pointer when you no longer need it.

It used free without using malloc. You can't release memory that hasn't been allocated.

Your code doesn't allocate any memory for the string. It simply copies a string from one string to the memory used by another (a string of spaces).
Memory is allocated using functions like malloc(), realloc(), etc. and then freed with free(). Since this memory was not allocated that way, passing the address to free() results in the error.

You did not use malloc() to allocate space in the heap for str. Therefore, str is allocated on the stack and cannot be deallocated with free(), but will be deallocated when str goes out of scope, i.e. after the function containing the declaration returns.

Related

Invalid (Aborted)core dumped error while using free() in C

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.

C - Dynamic allocation of a struct with non dynamics elements

I was wondering where a struct would be allocated in memory if I have something like this.
typedef struct {
int c;
} A;
A * a = (A)* malloc(sizeof(A));
a -> c = 2;
C would be allocated in the heap area, is that right?
Moreover, if I free the memory with
free(a);
What happens to the memory area occupied by C?
A * a = (A)* malloc(sizeof(A));
This line is incorrect, if you want to make an explicit cast, the syntax is (A*), not (A)*.
Anyway, yes, malloc allocates memory on the heap (in general and on non exotic system). What happens after depends on the OS and the implementation of the libc you use. Most often however, the memory freed is kept in a list for future use by malloc.
First of all you need to allocate the memory like A * a = (A*) malloc(sizeof(A));. In C when you allocate memory to a struct dynamically you need to provide total size of that struct and the return type conversion from void* to your data type. So your malloc call will allocate that much of memory and returns a void pointer to the first byte of that block of memory location.
So do not confuse that declaring variable inside a struct will be allocated from stack. Please see below:-
int c;// c is a automatic variable and memory will be allocated from stack
typedef struct {
int c;// c is not a automatic variable it is simply a data member of `struct A`
} A;
So in the second case memory will be allocated to c only when malloc will be called at run time that is dynamically and from heap. So your free call will simply release that memory at run time.
But
typedef struct {
int c;// c is not a automatic variable it is simply a data member of `struct A`
} A;
A a;// Here 'a' is a automatic variable so 'int c' is also become automatic here
//and memory for the entire struct A will be allocated from stack and
//you no need to use `free` here
Hope this is help.
A * a = (A)* malloc(sizeof(A));
Where a struct would be allocated in memory?
In C, the library function malloc allocate a block of memory on the heap. The program accesses this block of memory via a pointer that malloc returns. The memory is given by the operating system. If memory is not available NULL pointer is returned.
There is no need for casting of malloc in C. Your code has a typo, if anything it should be (A *).
What happens to the memory area occupied by C?
When the memory is no longer needed, the pointer pointing to the allocated memory should be passed to free which deallocates the memory so that it can be used again. For free(NULL); the function does nothing.
C11 standard (ISO/IEC 9899:2011):
7.22.3.3 The free function
Synopsis
#include <stdlib.h>
void free(void *ptr);
Description
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.
Fistly, C is a case-sensitive language.
int c is not the same as int C, so you might want to edit that in your question.
Now, lets answer your questions:
C would be allocated in the heap area, is that right?
Yes it is allocated from heap, subject to availability.
If you forget to release memory that was allocated, you will exhaust it.
Lets see what C11 standard says, C11 - Section 7.22.3 states,
The pointer returned if the allocation succeeds is suitably aligned so that it may be assigned to a pointer to any type of object with a fundamental alignment requirement and then used to access such an object or an array of such objects in the space allocated (until the space is explicitly deallocated). The lifetime of an allocated object extends from the allocation until the deallocation. Each such allocation shall yield a pointer to an object disjoint from any other object. The pointer returned points to the start (lowest byte address) of the allocated space. If the space cannot be allocated, a null pointer is returned. If the size of the space requested is zero, the behavior is implementation-defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.
Thats should suffice to justify why explicit typecasting in statement
A * a = (A)* malloc(sizeof(A));
is not required. So it should be
A * a = malloc(sizeof(A));
followed by test if a is NULL, if it is NULL, you shouldn't continue with further access.
What happens to the memory area occupied by C?
Again, referring to C11 standard, C11 - Section 7.22.3.3 which states,
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.
a in your code is equivalent to ptr above. Once freed, you can consider that the memory is returned to heap-pool for fresh allocations. There is no memory occupied by c now, and hence an access to c results in Undefined Behavior.
Refer C11 Standard, section J.2 Undefined Behavior:
An object is referred to outside of its lifetime (6.2.4).
The value of a pointer to an object whose lifetime has ended is used (6.2.4).
A * a = (A)* malloc(sizeof(A));
The compiler must be giving an error on this statement and if I am guessing correctly you want to cast the malloc return with (A *) which you should not do [check this].
In C language, a structure is a user-defined datatype which allows us to combine data of different types together and size of a structure variable is
size of all member variables + size of structure padding
So, when you dynamically allocate memory of sizeof(struct name) size, a block of memory of requested size gets allocated in heap and when you pass this pointer to free(), it deallocates that whole memory block.
What happens to the memory area occupied by C?
It is deallocated.
The lifetime of a dynamically allocated object is over when it is deallocated. So, when you do free(a), the life of a and all its data members is over and it is indeterminate now.
Additional:
A point to note here about free() is that it does not change the value of the pointer (passed to it) itself, hence it still points to the same (now invalid) location.
So, when you free a dynamically allocated memory it still points to the same location which is no more valid and accessing such memory is undefined behavior. From C Standard#6.2.4p2
The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it. An object exists, has a constant address,33) and retains its last-stored value throughout its lifetime.34) If an object is referred to outside of its lifetime, the behavior is undefined. The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.

C - pointer being freed was not allocated

I am trying to free a pointer that I assigned from a vector allocated with malloc(), when I try to remove the first element(index [0]), it works, when I try to remove the second(index [1]) I receive this error:
malloc: *** error for object 0x100200218: pointer being freed was not allocated
The code:
table->t = malloc (sizeof (entry) * tam);
entry * elem = &table->t[1];
free(elem);
You can only call (or need to) free() on the pointer returned by malloc() and family.
Quoting C11, chapter ยง7.22.3.3
[...] 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, table->t (or, &table->t[0]) is that pointer, not &table->t[1].
That said, free()-ing table->t frees the whole memory block, you don't need to (you can't, rather) free individually/ partially. See this answer for more info.
It works on the first element because &table->t[0] is equal to table->t. That's because the first element has the same address as the array itself (by definition of the array).
And since the array itself has an address that has been allocated, only that one can be freed.
malloc() works by allocating a single contiguous memory area, whose usable size is the single integer parameter passed by it. It returns a pointer for the allocated area.
You can only free the returned pointer once, and not a subset of it.
Arrays aren't objects in C, they're syntatic sugar to pointer arithmetic, which is probably the main headache of C programming and the area you should carefully study if you're committed to learning C.

Is malloc-ing a char the same as referencing a char array?

I think I have got my head mostly around the difference, but if I am correct, then this should be correct also:
1.)
char *string1 = (char*) malloc(runtime_determined_number);
2.)
char string2val[runtime_determined_number];
char *string2 = &string2val;
Here I would expect string1 and string2 to be the same, is this the case?
string1 and string2 are not pointed to the same memory area
string1 is a pointer pointing to a char array allocated dynamically with malloc
string2 is a pointer pointing to a char array allocated statically
They both point to uninitialized blocks of memory of the same length. So in that respect they are the same, yes.
Note that in case 1, you are responsible for freeing the memory once you're finished. And in case 2, you can't safely return the pointer from a function as the memory will go out of scope on exit.
Using malloc you are asking the OS for memory during runtime. If malloc succeeded you are able to work with the allocated memory. You must deallocate this memory later on!
In your second part you are creating a char-array and then assign its address to a pointer. In this case the memory is taken from the stack and will be freed automatically when the array goes out of scope.
Your char*s won't be the same as they will be pointing to different locations in memory. There is aminor chance they contain the same garbage as you have not initialized them...
They are similar in that they have the same type and have at least runtime_determined_number bytes allocated for them.
They are different in that:
the first version requires an explicit free() to avoid a memory leak;
the lifetime of the two objects may or may not be the same.
Note that the second version is only valid in C99, since it makes use of a variable-length array.

Dynamic memory allocation in C

i just experiment the things on the c language
could you answer my question regarding the program i've written
void main()
{
char *p,; // created a pointer pointing to string
p = (char *) malloc(50); // dynamically create 50 bytes.
strcpy(p, "this code is written about the dynamic allocation");
p += 20;
free(p);
}
Now could anyone tell me what is the effect of free(p) statement will the last 30 bytes will be freed of and used for the future memory allocation.? what would be the output?
You are not supposed to free any addresses but those returned by malloc(), calloc() or realloc(). And p + 20 is no such address.
http://codepad.org/FMr3dvnq shows you that such a free() is likely to fail.
The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed.
Does the pointer passed to free() have to point to beginning of the memory block, or can it point to the interior? is also worth reading.
Even if you could use free() on any pointer that points to a malloc'd memory - your could would free it twice since you are calling free() on more than one memory inside that area. And double-frees are evil as they can result in security holes.
It will result in Undefined Behavior.
The free() function shall cause the space pointed to by ptr to be deallocated; that is, made available for further allocation. If ptr is a null pointer, no action shall occur. Otherwise, if the argument does not match a pointer earlier returned by the calloc(), malloc(), posix_memalign(), realloc(), strdup() function, or if the space has been deallocated by a call to free() or realloc(), the behavior is undefined.

Resources