What is wrong with malloc? - c

Even if i allocate 0 byte the program works.Am i doing something wrong ?
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *str;
printf("memory address of str %p %p\n",&str,str);
/* Initial memory allocation */
str = (char*)malloc(0);
printf("memory address of str %p %p\n",&str,str);
strcpy(str,"abc");
printf(" string = %s %p %p\n", str,&str, str);
free(str);
return(0);
}

From malloc documentation:
If size is zero, the return value depends on the particular library
implementation (it may or may not be a null pointer), but the returned
pointer shall not be dereferenced.
Open Group says:
If the size of the space requested is 0, the behavior is
implementation-defined: the value returned shall be either a null
pointer or a unique pointer.
That means when size is 0, malloc() returns either NULL or a unique pointer that can be freed afterwards.

Am I doing something wrong?
Yes, the thing you are doing wrong is:
str = (char*)malloc(0);
strcpy(str,"abc");
If you allocate 0 bytes then you are only allowed to store 0 bytes there. Not 4 ('a', 'b', 'c' and the terminating null character).
Allocating some memory means reserving that memory for you, but even if some memory isn't reserved for you, you can sometimes still write to it - like nothing stops you from putting items in someone else's trolley at the supermarket.

Related

Heap Memory and malloc query

I am trying to get my head around dynamic memory allocation and was hoping someone could explain why the following code executes as it does.
#include <stdlib.h>
#include <string.h>
char* create_string(void);
int main(){
char* str1 = NULL;
char* str2 = NULL;
str1 = create_string();
str2 = (char*)malloc(11);
str2 = create_string();
printf("String 1 is: %s", str1);
printf("String 2 is: %s", str2);
free(str1);
}
char* create_string()
{
char* stack_str = "TestString";
char* heap_str = (char*)malloc(strlen(stack_str) + 1);
strcpy(heap_str, stack_str);
if(heap_str == NULL)
{
printf("Oh no");
return NULL;
}
return heap_str;
}
As far as I thought, to allocate memory on the heap, you have to use malloc with a size which allocates a block of memory and then use a function such as strcpy() or memcpy(), as I have done with str2 above (malloc 11 for the size of "TestString" plus one for the null terminator.)
I am just confused why assigning the result of create_string to str1 which is a null pointer which has not been allocated a block of memory produces the same output as str2.
Many thanks in advance!
"As far as I thought, to allocate memory on the heap, you have to use malloc with a size which..."
size in malloc() is number of bytes which is unsigned integer. Therefore syntactically str2 = (char*)malloc(11); is correct.
Both str1 and str2 are pointing to different memory locations from the heap containing "TestString". This is according to what you have programmed. However
str2 = (char*)malloc(11); returns 11 bytes of memory that can store character data type and returns a pointer to this location in heap. There is no issue in this.
However, in your code you have leaked this allocation when you assign create_string() pointer to it.
It is not wroking exactly as you think.
Firstly, C has constant strings, which will be initialized by double quotes. Those objects when used, actually return a pointer that points to the location of the initialized constant string array.
char * ptr="something" //"something" return a pointer to the location of the string array
// and is assigned to the ptr.
You don't need to allocate memory for constant string as they are managed by compilers. What's happening in the code is stack_str locates to this constant string array which is managed by the compiler. So it is always present. You create a memory block and stores the address in heap_str, and copies the stack_str contents to the dynamically allocated memory, and returns the pointer.
In effect,
str2 = (char*)malloc(11);
is not used for anything and is wasted. Hope you understands.
Edit: In your create_str(), you check heap_str isn't NULL AFTER strcpy(). If the malloc() failed for some reason, the program will still crash even if you check for NULL.

Need some explanation about malloc

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().

How can i check if char pointer is points nothing after allocated

I have allocated memory for a char pointer in this code and I wanted check does it points anything:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char *p = (char*) malloc(sizeof(char)*10);
if(*p == 0)
printf("The pointer points nothing !\n");
}
And I checked that if it doesn't point anything. Also I print of pointer's length and it prints "3" although it prints nothing. What is reason of this and how can I check if it points nothing ?
You need to modify the check to check against the returned pointer, not the content. Something like
if( p == NULL) {
fprintf(stderr, "The pointer points nothing !\n");
return 1;
}
should do. Quoting the standard regarding the return values:
The malloc function returns either a null pointer or a pointer to the allocated space.
The null pointer is returned in case of a failure, otherwise the pointer returned should be non-equal to a null pointer.
That said,
The initial content of the pointed memory is indeterminate, do not attempt to verify it. Quoting from the standard,
The malloc function allocates space for an object whose size is specified by size and
whose value is indeterminate.
That goes for your other question regarding "checking the length" of the pointer - it's pointless. Unless you have stored (write) some value into it - there's no point trying to measure the initial content, as it is indeterminate. You may eventually run into undefined behavior.
The cast for the returned pointer by malloc() and family is superfluous. It can be totally avoided in C.
sizeof(char) is guaranteed to be 1, in C. Thus, using sizeof(char) as a multiplier, is again not needed, per se.

Difference between initializing a string with (char *)malloc(0) and NULL

Why allocating a 0 size char block works in this case? But if I write char *string = NULL; it won't work.
I'm using Visual Studio.
int main()
{
char *string = (char *)malloc(0);
string[0] = 'a';
string[1] = 'b';
string[2] = 'c';
string[3] = 'd';
string[4] = '\0';
printf("%s\n",string);
return 0;
}
First let me state, as per the man page of malloc()
The malloc() function allocates size bytes and returns a pointer to the allocated memory. The memory is not initialized. If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().
a call like malloc(0) is valid itself, but then, we need to check the validity of the returned pointer. It can either
Return NULL
Return a pointer which can be passed to free().
but anyways, dereferencing that pointer is not allowed. It will cause out-of-bound memory access and cause undefined behaviour.
That said, two important things to mention,
Please see why not to cast the return value of malloc() and family in C.
Please check the return value of malloc() before using the returned pointer.
So, to answer your question,
Difference between initializing a string with (char *)malloc(0) and NULL
Do not use malloc(0) in this case, as a NULL check on the pointer may fail, giving the wrong impression of a valid allocation of the memory to the pointer. Always use NULL for initialization.
The above code invokes undefined behavior. You have allocated insufficient memory and you are accessing invalid addresses.
According to the specifications, malloc(0) will return either "a null pointer or a unique pointer that can be successfully passed to free()".
malloc definition:
Allocates a block of size bytes of memory, returning a pointer to the
beginning of the block.
The content of the newly allocated block of memory is not initialized,
remaining with indeterminate values.
If size is zero, the return value depends on the particular library
implementation (it may or may not be a null pointer), but the returned
pointer shall not be dereferenced.
Taken from here and found this related question.

Why can I assign a longer string to a pointer in C?

#include <stdio.h>
#include <stdlib.h>
int main()
{
char *ptr = malloc(sizeof(char) * 1);
ptr = "Hello World";
puts(ptr);
getchar();
}
im not a malloc() expert but isn't that code supposed to give an error since i allocated only one byte but assigned a value that contains 11 bytes to *ptr pointer ?
or does the H get stored in the place i assigned and then the rest of the string just goes in the places after it ?
You are reassigning the pointer 'ptr' to another block of memory, so you won't see any error. However, the block of memory (size 1) that you allocated is "lost" and leads to a memory leak.
When using malloc you're requesting some memory and malloc returns the first address of that memory (if it can be given). When you re-assign the pointer you're not doing anything with the memory it points to. You just change what the pointer points to.
What you're doing here is technically valid C but you're creating a memory leak because you lose the address of the malloced memory, which you must free when you're done with it.

Resources