4

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

}
KamilCuk
  • 120,984
  • 8
  • 59
  • 111

7 Answers7

4

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

Mureinik
  • 297,002
  • 52
  • 306
  • 350
2

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.

Community
  • 1
  • 1
H.S.
  • 11,654
  • 2
  • 15
  • 32
2
  • 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() */
Luis Colorado
  • 10,974
  • 1
  • 16
  • 31
0

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

Achal
  • 11,821
  • 2
  • 15
  • 37
  • `malloc() doesn't allocate exactly 5 bytes of memory, it does allocate some additional memory to maintain heap information` very imprecise. Implementation of malloc **may** do so but many implementations do not. – 0___________ Apr 13 '19 at 11:19
  • True @P__J__ its implementation specific – Achal Apr 13 '19 at 11:20
  • @P__J__, you don't know that.... `malloc()` implementation is free to save (and much more secure) the metadata of the allocation in a separate place, not with the chunk of data just given to the client code. Client code errors normally go through overwritting the metadata by passing over the bounds of the allocated chunk, so it would be safe to save those in another place. – Luis Colorado Apr 16 '19 at 15:17
  • @LuisColorado implementation is free to do what it only wants. All your deliberations do not have any sense as standard does not say a word about implementation of the malloc. You probably do not know about it – 0___________ Apr 16 '19 at 18:21
  • 1
    Your assumptiion that malloc _always_ stores info in the chunk given to the memory requestor and that it always allocates more than the user requested is what is false.... Precisely by the reason you state in your comment that _implementation is free to do what it only wants_ Read once more my comment, instead of saying that what I say has no sense. If you are citing something said by others, please state so in your comment. Reread it also, as you have written it. – Luis Colorado Apr 17 '19 at 03:22
0

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 -]
Ljm Dullaart
  • 4,273
  • 2
  • 14
  • 31
0

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.

Community
  • 1
  • 1
Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
0

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

0___________
  • 60,014
  • 4
  • 34
  • 74