C Memory Allocation Problems

Source: Internet
Author: User
Malloc:
1. malloc allocates new memory and uses parameters to bring back the applied memory pointer (the second-level pointer is required or the returned memory pointer is used)
Error program: # include <stdio. h> # include <stdlib. h> void getmemory (char * P) {P = (char *) malloc (100); strcpy (P, "Hello World");} int main () {char * STR = NULL; getmemory (STR); printf ("% s/n", STR); free (STR); Return 0 ;}
Running result: the program crashes. the malloc in getmemory cannot return dynamic memory. Free () is dangerous for STR operations.
Cause Analysis: // malloc (STR) is a value transfer operation for the pointer Str. STR is copied in getmemory and cannot return the requested memory address through the parameter, STR is still null. The free (null) operation is dangerous. // Malloc () in the getmemory function allocates a new memory to P. After the function is executed, P cannot be found because STR does not get the P value, as a result, the newly allocated memory pointed to by P is not free and the memory leaks.
Correct Solution: # include <stdio. h> # include <string. h> # include <stdlib. h> void getmemory (char ** p) {* P = (char *) malloc (100); strcpy (* P, "Hello World");} int main () {char * STR = NULL; getmemory (& Str); printf ("% s \ n", STR); free (STR); Return 0 ;}or:
#include <stdio.h>#include <string.h>#include <stdlib.h>char* getmemory(char *p){    p=(char *) malloc(100);    strcpy(p,"hello world");    return p;}int main( ){    char *str=NULL;    str=getmemory(str);    printf("%s\n",str);    free(str);    return 0;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.