Question

I have a simple C program about assign char pointer and malloc like this

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char str[] = "0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789";
    char* str1 = malloc(sizeof(char*));
    strcpy(str1, str);
    printf("%s\n\n", str1);

    char* str2 = malloc(sizeof(char*));
    str2 = str1;    
    printf("%s\n", str2);

    return 0;
}

And the result is:

0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789

0123456789 0123456789 01!

So why the str2 just gets 25 characters from str1? And where is the "!" (in the end of str2) come from?

Could you help me? Thanks!

Was it helpful?

Solution

You didn't malloc enough space. sizeof(char *) is the amount of memory required to hold a pointer (NOT anything to do with where that pointer is pointing).

Change both mallocs to: malloc(sizeof str), or malloc(strlen(str) + 1).

Also, str2 = str1 causes a memory leak. It makes the pointer str2 point to where str1 points, and then you have that malloc'd block with nothing pointing to it.

In your original code, when you write into memory you don't own, anything could happen; it's not really useful to try and investigate exactly why you get some particular garbage instead of some other particular garbage.

OTHER TIPS

Your sizeof is wrong, you're malloc-ing 4 or 8 bytes, depending on your pointer size, you should malloc(sizeof(str) since that is what you're copying into it.

Also, note that str2 = str1 simply overwrites the str2 pointer, so you have a memory leak, as the malloc in your str2 initialization gets lost.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top