简体   繁体   中英

trouble printing after allocating memory

After using malloc , name gets printed but after allocating memory and typing in a string , puts doesn't print the string at all, neither does printf ...why is this?

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


int main()
{
    char *name;
    int size;
    printf("enter the size if name below\n");
    scanf("%d", &size);
    name  =(char*) malloc(size * sizeof(char));//since my compiler returns pointr of type    void, you have specify whether (int*) or (char*)
    if (name== NULL)
    printf("memory allocation failed,,,\n");
    printf("%s\n",name);
    printf("enter name below\n");
    scanf("%s", name);
    printf("name is\n%s", name);
    name = (char*)realloc(name, 100*sizeof(char));
    if (name == NULL)
    printf("failed\n");
    gets(name);
    getchar();
    puts(name);
    free(name);
    return 0;
}

First things first, malloc/realloc do not return void , they return void* which is perfectly capable of being implicitly cast to any other pointer type. It's a bad idea to do so explicitly in C since it can hide certain subtle errors.

In addition, sizeof(char) is always one, you do not need to multiply by it.

Thirdly, using gets is a very bad idea since there's no way to protect against buffer overflow. There are much better ways to do user input.

As to the specific problem, I suspect it's most likely still sitting around at the getchar . gets will get a line from the user (including the newline character) but, unless you enter another character (probably a full line if it's using line-based I/O), it will seem to hang. Check this by simply hitting ENTER again after you've entered the name.

gets()处尝试fgets()scanf() gets() ,它将起作用

The program that you have posted causes undefined behavior . This is because of

printf("%s\n",name);

There is nothing in the variable name and you are trying to print the value in the allocated memory. First you need to assign some value to name before printing it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM