开发者

C Language - Malloc unlimited space?

I'm having difficulty learning C language's malloc and pointer:

What I learned so far:

  • Pointer is memory address pointer.

  • malloc() allocate memory locations and returns the memory address.

I'm trying to create a program to test malloc and pointer, here's what I have:

#include<stdio.h>

main()
{
char *x;
x = malloc(sizeof(char) * 5);

strcpy(*x, "123456");
printf("%s",*x); //Prints 123456

}

I'm expecting an error since the size I provided to malloc is 5, where I put 6 characters (123456) to the memory location my point开发者_开发问答er points to. What is happening here? Please help me.

Update

Where to learn malloc and pointer? I'm confused by the asterisk thing, like when to use asterisk etc. I will not rest till I learn this thing! Thanks!


You are invoking undefined behaviour because you are writing (or trying to write) beyond the bounds of allocated memory.

Other nitpicks:

  • Because you are using strcpy(), you are copying 7 bytes, not 6 as you claim in the question.
  • Your call to strcpy() is flawed - you are passing a char instead of a pointer to char as the first argument.
  • If your compiler is not complaining, you are not using enough warning options. If you're using GCC, you need at least -Wall in your compiler command line.
  • You need to include both <stdlib.h> for malloc() and <string.h> for strcpy().
  • You should also explicitly specify int main() (or, better, int main(void)).
  • Personally, I'm old school enough that I prefer to see an explicit return(0); at the end of main(), even though C99 follows C++98 and allows you to omit it.

You may be unlucky and get away with invoking undefined behaviour for a while, but a tool like valgrind should point out the error of your ways. In practice, many implementations of malloc() allocate a multiple of 8 bytes (and some a multiple of 16 bytes), and given that you delicately do not step over the 8 byte allocation, you may actually get away with it. But a good debugging malloc() or valgrind will point out that you are doing it wrong.

Note that since you don't free() your allocated space before you return from main(), you (relatively harmlessly in this context) leak it. Note too that if your copied string was longer (say as long as the alphabet), and especially if you tried to free() your allocated memory, or tried to allocate other memory chunks after scribbling beyond the end of the first one, then you are more likely to see your code crash.

Undefined behaviour is unconditionally bad. Anything could happen. No system is required to diagnose it. Avoid it!


If you call malloc you get and adress of a memory region on heap. If it returns e.g. 1000 you memory would look like:

Adr  Value
----------
1000 1
1001 2
1002 3
1003 4
1004 5
1005 6
1006 0

after the call to strcpy(). you wrote 7 chars (2 more than allocated).

x == 1000 (pointer address)

*x == 1 (dereferenced the value x points to)

There are no warnings or error messages from the compiler, since C doesn't have any range-checking.


My three cents:

  1. Use x, as (*x) is the value that is stored at x (which is unknown in your case) - you are writing to unknown memory location. It should be:

    strcpy(x, "123456");

  2. Secondly - "123456" is not 6 bytes, it's 7. You forgot about trailing zero-terminator.

  3. Your program with it's current code might work, but not guaranteed.

What I would do:

#include<stdio.h>

main()
{
    char str[] = "123456";
    char *x;
    x = malloc(sizeof(str));

    strcpy(x, str);
    printf("%s",x); //Prints 123456

    free(x);
}


Firstly, there is one problem with your code:

x is a pointer to a memory area where you allocated space for 5 characters. *x it's the value of the first character. You should use strcpy(x, "123456");

Secondly, the memory after your 5 bytes allocated, can be valid so you will not receive an error.


#include<stdio.h>

main()
{
char *x;
x = malloc(sizeof(char) * 5);

strcpy(x, "123456");
printf("%s",x); //Prints 123456

}

Use this...it will work

See difference in your & mine program

Now here you are allocating 5 bytes & writing 6 byte so 6th byte will be stored in next consecutive address. This extra byte can be allocated to some one else by memory management so any time that extra byte can be changed by other program because 6th byte is not yours because you haven't malloc'd that.. that's why this is called undefined behaviour.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜