[help] Studying Malloc

Morning every one
I started to play around with memory allocation in c/c++, now since I didn't have a teacher, I decided to ask these questions as am noob to this part.

Am trying to use this char namez[35] to be assigned to this function getname () per say, now I needed some clarification as to whether am getting this correctly, code goes like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h>
#include <stdlib.h>

char* getname()
{
    char* fname[35] ="Shawn Little";
    fname = (char*)malloc(35*sizeof(char));
}

int main()
{ 
  char namez[50];
  namez = (char*) malloc(50*sizeof(char));
ZeroMemory(namez,50*sizeof(char));
names = getname();
return 0;
 }


Need advise here as this is the first time doing this :) am typing from my BlackBerry.
Last edited on
First of all, what is ZeroMemory? I don't know.
Second, you need to know more about array and pointer to understand dynamic allocation. You cannot change the fname or namez pointers as they are constant pointers. (Array name is a constant pointer)
Apart from leaking memory, your code is full of errors. It should be something like this-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* getname()
{
    char*p = (char*)malloc(35*sizeof(char)); // allocating memory
    strcpy(p, "Shawn Little");

    return p;
}

int main()
{
    char* namez;

    namez = getname();

    printf("%s", namez);

    free(namez); // freeing memory

    return 0;
 }
Last edited on
Topic archived. No new replies allowed.