Malloc vs array in C

I am taking a course from the MOOC CS50 from Harvard. The last lecture I read was about allocating memory and pointers (two completely new concepts).

It has been shown that it malloc(10*sizeof(char))allocates enough bytes on the heap to store 10 characters and returns a pointer to the first byte, which can be stored in another variable as follows char *x = malloc(10*sizeof(char)). To free memory you must use free(x).

But there is another way to make the computer reserve enough memory to store 10 characters, i.e. char c[10].

  • Is there a ctype pointer in the code snippet above char*?
  • Does heapchar c[10] memory save how malloc?
  • Ways to allocate equivalent memory?
  • char c[3] = "aaa";free(c);returns a runtime error; therefore it seems that I cannot free the memory that I allocated with char c[3]. Why is this?

I would really appreciate an answer like the one who just found out about pointers.

+4
source share
4 answers

What was taught is that it malloc(10*sizeof(char))allocates enough bytes on the heap to store 10 characters and returns a pointer to the first byte, which can be stored in another variable as follows char *x = malloc(10*sizeof(char)). To free memory, use free(x).

" " - , C-. C , , C .

- , - C, , . C :

, . : , , .

(C2011, 6.2.4/1)

, malloc(), (in), x, "" . , , free(). x, , x, 10 char s.

() , . , , , .

10 , .. char c[10].

, .

  • c char*?

. c 10 char s. , . , , , : - . , , , SO.

, c , x, , x () , .

  1. char c[10] malloc?

c , . , , c . , , , /, , , , .

  1. ?

. malloc() , . , .

  1. char c[3] = "aaa";free(c); ; , , char c[3]. ?

, free()

[I] f , free realloc, undefined.

(C2011, 7.22.3.3/2)

( - ), , , .

, , , free() - , , ( ) . (, ), .

+5
  • c char *?

, . char.

, , , , .

  1. char c [10] malloc?

. , .

, malloc() , " " .

char c[10]; .

  • ( {}), . , (, ).
  • ( ), . .
  1. ?

.

char c [3] = "aaa"; free (c); ; , , char c [3]. ?

free() - .. malloc(), calloc() realloc() NULL ( free() ).

c , , , . , free() undefined. , .

+5

"char c [10];" , , , , ( ).

(, - ):

, var [size], , . - (, , ).

+2

:

, c x : x - , char*, c - char[10], .

, x c : x, char. , c, char . ,

printf("sizeof(x) = %zd\n", sizeof(x));
printf("sizeof(*x) = %zd\n", sizeof(*x));
printf("sizeof(c) = %zd\n", sizeof(c));

sizeof(x) = 8
sizeof(*x) = 1
sizeof(c) = 10

64- . sizeof(x) , , sizeof(*x) , x, sizeof(c) , char .

, c , x C?

- . , , , . C , . - sizeof() ( , sizeof(x) != sizeof(c)), - &. c . , c[3]. *(c+3), c , c+3, . , , .


, , :

  • malloc() , , free() , malloc().

    . malloc() . malloc() , . , - , . - . . , , .

    , . , , , C. - , malloc'ed . , , .

  • char c[10];
    

    ( struct) . , main() ( main(), exit()).

  • char c[10];
    

    . , , ( {}).

    , .

  • char c[10];
    

    a struct, -. , (struct). , , - , - , - , : ( ).

+2

Source: https://habr.com/ru/post/1691282/