Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help with malloc in C programming. It is allocating more space than expected

Tags:

c

malloc

Let me preface this by saying that i am a newbie, and im in a entry level C class at school.

Im writing a program that required me to use malloc and malloc is allocating 8x the space i expect it to in all cases. Even when just to malloc(1), it is allocation 8 bytes instead of 1, and i am confused as to why.

Here is my code I tested with. This should only allow one character to be entered plus the escape character. Instead I can enter 8, so it is allocating 8 bytes instead of 1, this is the case even if I just use a integer in malloc(). Please ignore the x variable, it is used in the actual program, but not in this test. :

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


int main (int argc ,char* argv[]){

    int x = 0;
    char *A = NULL;
    A=(char*)malloc(sizeof(char)+1);
    scanf("%s",A);
    printf("%s", A);
    free(A);
    return 0;
}
like image 652
user601768 Avatar asked Feb 03 '11 15:02

user601768


1 Answers

 A=(char*)malloc(sizeof(char)+1);

is going to allocate at least 2 bytes (sizeof(char) is always 1). I don't understand how you are determining that it is allocating 8 bytes, however malloc is allowed to allocate more memory than you ask for, just never less.

The fact that you can use scanf to write a longer string to the memory pointed to by A does not mean that you have that memory allocated. It will overwrite whatever is there, which may result in your program crashing or producing unexpected results.

like image 56
Joseph Stine Avatar answered Oct 05 '22 23:10

Joseph Stine