I have below code where I have commented when I get segmentation fault and when not.
Originally I got segmentation fault and then I could figure out that probably I cannot initialize my char pointer locations like "abcd". But I am not able to understand - WHY?
I thought testString = "abcd"; will put a at first memory address, b at second and so on ...
Segmentation fault occurs when trying to free memory, based on how I initialize memory location.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char* testString = malloc(sizeof(char) * 5);
printf("Size of char is: %d\n", sizeof(char));
printf("Size of int is: %d\n", sizeof(int));
for(int i = 0; i < 5; i++)
{
printf("Pointer addresses are: %p\n", testString + i);
}
char* tempPtr = testString + 2;
printf("My temp pointer address = %p\n", tempPtr);
// This gives me segmentation fault ....
testString = "abcd";
// This will not give me segmentation fault ....
//int count = 65;
//for(int i = 0; i < 5; i++)
//{
// testString[i] = count + i;
//}
printf("Printing character...\n");
for(int i = 0; i < 5; i++)
{
printf("Characters are: %c\n", testString[i]);
}
printf("Freeing memory...\n");
free(testString);
//printf("Access after freeing >>%c<<\n", tempPtr[0]);
//free(testString);
}
Based on #M.M. and #Jonathan's comment I understood that with testString = "abcd"; my testString will point to a memory location where string "abcd" was created and since I didn't malloc'ed it I cannot free it. Also, since my original pointer to heap memory (which I got using malloc) is gone, so it is waste of memory or memory lead.
So, does it means that when I use printf statement like printf("Printing character...\n");, this is also a memory leak? Then how do I avoid it? Looping and inserting into char* is certainly a bad idea.
this line:
testString = "abcd";
is overlaying the pointer given by the call to malloc() with the address of the string literal: "abcd" this results in a memory leak because the original pointer to the allocated memory is lost.
In C, when copying a string, it 'should' be handled by the functions: strcpy() and strncpy() which will not corrupt the pointer contained in testString.
strcpy( testString, "abcd" );
strncpy( testString, "abcd", strlen( "abcd" ) );
Naturally, once the pointer to the allocated memory has been overlayed/destroyed by the assignment statement: testString = "abcd";, the new value placed into testString must not be passed to free()
the seg fault would be happening at the call to free(), not at the incorrect assignment of a new pointer to testString.
Using printf is not a memory leak. Memory leaks occur when a pointer is allocated via malloc [or, herein, strdup] and there is no corresponding free call for it.
Also, trying to free a pointer that has not been allocated is another type of error. It [probably] won't segfault, but free will complain.
Here's a simplified version of your program that illustrates some of the ways you can do this:
#include <stdio.h>
#include <string.h>
#include <malloc.h>
int opt_segv;
char *temp = "abcd";
void
dostr(char *str,int modflg)
{
printf("\n");
printf("dostr: %s\n",str);
if (modflg)
str[modflg] = 'm';
printf("dostr: %s\n",str);
}
void
test1(void)
{
int len;
char *testString;
len = strlen(temp);
testString = malloc(len + 1);
strcpy(testString,temp);
dostr(testString,1);
free(testString);
}
void
test2(void)
{
char *testString;
testString = strdup(temp);
dostr(testString,2);
free(testString);
}
void
test3(void)
{
char *testString;
// passing a pointer to a string _constant_ -- do _not_ modify
testString = temp;
dostr(testString,opt_segv ? 3 : 0);
}
int
main(int argc,char **argv)
{
char *cp;
--argc;
++argv;
for (; argc > 0; --argc, ++argv) {
cp = *argv;
if (*cp != '-')
break;
switch (cp[1]) {
case 's': // generate segfault
opt_segv = 1;
break;
}
}
test1();
test2();
test3();
return 0;
}
You can run the program with -s to simulate the string constant modification that caused your segfault.
This question has content relevant to answer of my question but doesn't have detailed answer. #Jonathan's comments answers all my questions but he hasn't put forward a detailed answer so I am writing my answer so that folks who will visit further can have detailed explanation:
I created a pointer and allocated some space on "heap segment" of the memory, now my pointer was pointing to that memory location on heap.
Code relevant for all this is - char* testString = malloc(sizeof(char) * 5);.
Now, when I dis this - testString = "abcd"; then string "abcd" is created in "text/code segment" (or in some implementation data segment) of the memory and memory address is returned and assigned to my pointer testString.
What happens is that my original pointer which was pointing a memory location on heap is lost and the pointer started pointing to a memory location on text/code segment of the memory.
Implication of all this:
It has resulted in memory leak because my original pointer which was pointing to the heap memory is lost, so now I have no way to free that heap memory and hence memory leak.
When I will try to free that memory using free(testString); then I will get segmentation fault (this is exactly what has happened to me) because free() can only be used to free the memory which is allocated using either malloc, calloc or realloc. Now, since the pointer testString is pointing to a memory location on text/code segment and I had not allocated that memory using some C memory allocation method, so I cannot free it using free() and if I do so then I get segmentation fault.
When I do testString = "abcd" (when testString is a pointer) then I cannot access the memory location pointed by testString because the memory allocated is read-only in text/code segment of the memory. So, testString[0] = 'x' will also result in segmentation fault.
What happens when I do printf("hello, world")?:
This will create "hello, world" string as read-only in text/code segment of memory. I verified that it does create in text/code segment in C99 implementation using size command.
Related
There are some related discussions about my problem but there are no clearly explanations about my problem.
I thought that I must free() whatever I malloc(), no matter when or where but I have to do it, to prevent a memory leak.
So i have the following program:
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int *ptr;
ptr = malloc(256);
if (ptr == NULL) {
printf("Out of memory\n");
return 1;
}
*ptr = 10;
printf("The value of PTR is:\t%d\n",*ptr);
free(ptr);
return 0;
}
I have a pointer and I dynamically allocated some memory (256), then I checked for NULL letter I free() it.
Until here everything is OK: to the pointer was dynamically allocated some memory and then I free() it.
Now i will use a char pointer this time and after i will dynamically allocated some memory (256), i will point that pointer to a string literal, lets say MICHI:
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
char *ptr;
ptr = malloc(256);
if (ptr == NULL) {
printf("Out of memory\n");
return 1;
}
ptr = "michi";
printf("%s",ptr);
free(ptr);
return 0;
}
Here I am doing something wrong because if i try to free() it, well it will not work because it happens that i'm going to free a non-heap object.
So i'm lost in here, because i thought that everything you malloc() you have to free() it.
What exactly make that pointer, after points to a string literal, to not need to be free()ed
ptr = malloc(256);
...
ptr = "michi";
printf("%s",ptr);
free(ptr);
As you allocate memory to ptr and then you make it point to string literal. Thus pointer ptr no longer points to memory allocated by malloc.
And to free memory not allocated by malloc or similar functions cause error in program.
Do this instead:
strcpy(ptr,"michi");
In the first program you allocated memory
ptr = malloc(256);
and initialized its first sizeof( int ) bytes with integer value 10.
*ptr = 10;
The pointer itself was not changed. So in this statement
free(ptr);
pointer ptr points to the memory that was allocated using malloc.
In the second program you allocated memory the same way as in the first program
ptr = malloc(256);
But then you reassigned the pointer itself with the address of the first character of string literal "michi"
ptr = "michi";
Compare the left sides of this assignment
*ptr = 10;
and of this assignment
ptr = "michi";
As you see they are different. In the first case you are changing the allocated memory while in the second case you are changing the pointer itself.
Thus in this statement
free(ptr);
pointer ptr does not point to the memory that was previously allocated. It points to the memory occupied by the string literal that was not allocated using malloc.
Thus this statement is wrong and the program has a memory leak because the previous memory that was allocated using malloc was not freed,
Because constant literals are stored in a way for the lifetime of the program, in a read-only region of memory in most of the platforms.
When you use free you are trying to free the memory allocated, not the pointer itself, that's why it's not gonna work if you try to do that in a read-only region of memory
When you reassign your pointer you're losing track of the allocated memory and therefore creating a memory leak.
The memory leak is created because you first allocated the memory and assign it to your pointer, when you've a pointer pointing to it you can easily free that memory, but when you don't have any more reference to that memory you can't.
That's what's happening, when assign the literal to the pointer there's no more reference to that address, it was allocated but it's not reachable anymore, in this way you can't free the memory.
The problem is that you have lost the pointer the second you assigned another value to it:
ptr = malloc(256);
if (ptr == NULL) {
printf("Out of memory\n");
return 1;
}
// here you should free your memory
ptr = "michi";
printf("%s",ptr);
// this fails, because ptr now points to the const static string "michi" you have coded yourself. The assignment didn't copy it, just changed what ptr points to.
free(ptr);
Try this.
#include <stdio.h>
int main(void)
{
char *str:
str = (char*)malloc(sizeof(str) * 4);
printf("Addr of str before: %p\n", str);
str = "Joe";
printf("Addr of str after: %p\n",str);
return(0);
}
/* you will get the following addresses:
Addr of str before: 0x51fc040
Addr of str after: 0x4006f0
this is becuase you changed where str points to. 0x51fc040 is memory allocated using malloc and 0x4006f0 is the memory Adress of the string literal "Joe".
I would advice the following...*/
#include <stdio.h>
int main(void)
{
char *str;
str = (char*)malloc(sizeof(str) * 4);
printf("Addr of str before: %p\n", str);
str =strncpy(str, "Joe", 4);
printf("Addr of str after: %p\n",str);
free(str);
return (0);
}
/* you will get the following addresses:
Addr of str before: 0x51fc040
Addr of str after: 0x51fc040
This is because strncpy copies the string literal to the memory dynamically allocated. and it is safer than stcpy, since it prevents buffer overflow
I've spotted the error in my program and decided to write a simple one, which would help me understand what's going on. Here it is :
#include <stdio.h>
#include <stdlib.h>
char * first()
{
char * word = malloc(sizeof(char) * 10);
word[0] = 'a';
word[1] = 'b';
word[2] = '\0';
return word;
}
char * second ()
{
char * word = malloc(sizeof(char) * 10);
word = "ab";
return word;
}
int main ()
{
char * out = first();
printf("%s", out);
free(out);
out = second();
printf("%s", out);
free(out);
return 0;
}
The first() function is working properly, but the second() (exactly the free(out) ) genarates error:
Error in `./a.out': munmap_chunk(): invalid pointer: 0x0000000000400714 ***
ababAborted (core dumped)
I don't understand why the first function is correct, but the second isn't. Could anyone explain why?
In the function second(), the assignment word = "ab"; assigns a new pointer to word, overwriting the pointer obtained through malloc(). When you call free() on the pointer later on, the program crashes because you pass a pointer to free() that has not been obtained through malloc().
Assigning string literals does not have the effect of copying their content as you might have thought. To copy the content of a string literal, use strcpy():
strcpy(word, "ab");
In function char * second
char * word = malloc(sizeof(char) * 10);
word = "ab";
The second statement word = "ab"; changes word to point away from the allocated memory.You are not copying the string "ab" to the area of heap allocated by malloc.
And to free a memory that is not allocated by malloc or similar functions crashes your program.
Attempting to free an invalid pointer (a pointer to a memory block that was not allocated by calloc, malloc, or realloc) may affect subsequent allocation requests and cause errors.
You should use here strcpy as also suggested by others.
I'm working on learning how to properly deal with pointers, arrays etc in C. I'm a little confused on allocating the memory for them and then freeing that memory. The following is some test code I slapped together:
char *test[150000];
char **ptr;
for(int i = 0; i < 150000; i++)
{
test[i] = malloc(15*sizeof(char));
test[i] = "This is a test";
printf("test[%i] = %s located at %p\n",i,test[i],&test[i]);
}
for(int i=0; i < 150000; i++)
{
printf("Trying to free memory from %p\n",&test[i]);
ptr = &test[i];
free(ptr);
printf("Array item %i has been freed...",i);
}
The output yields the following:
[... Truncated]
test[149997] = This is a test located at 0x7fff581fbcc8
test[149998] = This is a test located at 0x7fff581fbcd0
test[149999] = This is a test located at 0x7fff581fbcd8
Trying to free memory from 0x7fff580d6d60
test2(17599,0x7fff7776f310) malloc: *** error for object 0x7fff580d6d60: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6
sh-3.2#
It appears that when I try and free the pointer allocated, I get an error... Any ideas / pointers on where I'm screwing up would be greatly appreciated.
test[i] = malloc(15*sizeof(char));
This is ok, except that (a) it could be written as test[i] = malloc(15);, and (b) you don't check whether malloc succeeded.
test[i] = "This is a test";
This does not copy the contents of the string "This is a test" into the memory you just allocated. Rather, it's a pointer assignment, causing test[i] to point to the memory for the string literal. It creates a memory leak, since you no longer have a pointer to the memory you allocated with malloc. You probably want to use strcpy.
...
ptr = &test[i];
free(ptr);
Here you free the memory assigned to the string literal, not the memory you allocated.
Correction: that's not what it does. It tries to free the pointer object itself, which doesn't even make sense. (Incidentally, the argument to free doesn't have to be an object name; free(&test[i]) would be equally legal -- and equally incorrect.)
Assuming you fix the allocation problem, what you want is simply:
free(test[i]);
char *test[150000];
char **ptr;
for(int i = 0; i < 150000; i++)
{
test[i] = malloc(15*sizeof(char));
/*test[i] = "This is a test";*/ // Fix1
printf("test[%i] = %s located at %p\n",i,test[i],&test[i]);
}
for(int i=0; i < 150000; i++)
{
printf("Trying to free memory from %p\n",&test[i]);
/*ptr = &test[i];*/ //Fix2
free(test[i]); //Fix3
printf("Array item %i has been freed...",i);
}
Fix1:
Heap Memory is allocated and stored into test[i]. So test[i] has valid address. But again test[i] address is overridden using this statement test[i] = "This is a test"; If you want to copy the string into test[i] use strcpy.
Suppose if you like to assign like this test[i] = "This is a test"; do not allocate dynamic memory before this & no need to free also.
Fix2&Fix3:
The allocated address is stored in test[i] not in &test[i]. So just free that address present in test[i]. No need to use intermediate variable also. If required to use intermediate variable prefer to use char *ptr.
I am puzzled by this response.Can anyone help me on this and point out where I am making a mistake? The output at codepad is "memory clobbered before allocated block"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char *s = (char *)malloc(10 * sizeof(char));
s = "heel";
printf("%s\n",s);
printf("%c\n",s[2]);
printf("%p\n",s);
printf("%d\n",s);
free(s);
return 0;
}
You're trying to free constant memory with:
free(s); // cannot free constant "heel"
What you're doing is allocating a piece of memory and storing its location (char *s). You are then overwriting that reference with one to a string constant "heel" (memory leak), which cannot be freed. To make this behave as desired, you should be copying the constant string to the memory you allocated:
strcpy(s, "heel");
Here is an example for getting user input:
char *input = malloc(sizeof(char) * 16); // enough space for 15 characters + '\0'
fgets(input, 16, stdin);
// do something with input
free(input);
To expand on #TimCooper's answer:
first you do: char *s = (char *)malloc(10 * sizeof(char));
then: s = "heel";
The first line allocates memory and assigns the location of that memory to s. But the second line reassigns s to the memory location of constant string heel on the stack!
Which means you try and free() memory on the stack, which is illegal. AND you leak memory, since what you first allocated to s is now inaccessible.
If you want to write a string into the memory pointed by s, you should use something like strcpy() (or, better, strncpy()).
You cannot free(s) - it's constant memory.
Try to change s = "heel"; with strcpy(s,"heel");
char *s = (char *)malloc(10 * sizeof(char));
s = "heel";
Doesn't do what you think, or what you would expect with more modern languages
The first line allocates some memory for 10chars and returns the address of it.
The second line changes that address to point to a constant block of memory allocated at compile time, containing "heel" losing the link to the allocated memory - leaking it
I don't understand why, in this code, the call to "free" cause a segmentation fault:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *char_arr_allocator(int length);
int main(int argc, char* argv[0]){
char* stringa = NULL;
stringa = char_arr_allocator(100);
printf("stringa address: %p\n", stringa); // same address as "arr"
printf("stringa: %s\n",stringa);
//free(stringa);
return 0;
}
char *char_arr_allocator(int length) {
char *arr;
arr = malloc(length*sizeof(char));
arr = "xxxxxxx";
printf("arr address: %p\n", arr); // same address as "stringa"
return arr;
}
Can someone explain it to me?
Thanks,
Segolas
You are allocating the memory using malloc correctly:
arr = malloc(length*sizeof(char));
then you do this:
arr = "xxxxxxx";
this will cause arr point to the address of the string literal "xxxxxxx", leaking your malloced memory. And also calling free on address of string literal leads to undefined behavior.
If you want to copy the string into the allocated memory use strcpy as:
strcpy(arr,"xxxxxxx");
The third line of char_arr_allocator() wipes out your malloc() result and replaces it with a chunk of static memory in the data page. Calling free() on this blows up.
Use str[n]cpy() to copy the string literal to the buffer instead.
When you write a constant string in C, such as "xxxxxx", what happens is that that string goes directly into the executable. When you refer to it in your source, it gets replaced with a pointer to that memory. So you can read the line
arr = "xxxxxxx";
Treating arr as a number as something like:
arr = 12345678;
Where that number is an address. malloc has returned a different address, and you threw that away when you assigned a new address to arr. You are getting a segfault because you are trying to free a constant string which is directly in your executable -- you never allocated it.
You are setting arr to the return value of malloc(), which is correct. But you are then reassigning it to point at the string constant "xxxxxxx". So when you call free(), you're asking the runtime to free a string constant, which causes the seg fault.