is Malloc allocating more memory then needed?

牧云@^-^@ 提交于 2020-07-22 21:34:06

问题


This is an C assignment for school but I'm running into to something strange that I don't know if it is normal or not.

I have to take command line arguments and an example of one is

-ia.b

so within my program I dynamically allocate memory with malloc

char *fileName = NULL;
fileName = malloc(strlen(argv[i]) * sizeof(char));
//error testing etc
strcpy(fileName, argv[i]);

Works fine, but I look into memory via visual studio debugger this is what become allocated at the memory location which to me is more room then needed:

0x01608b98 "ÍÍÍÍÍýýýýB`\x1˜?`\x1\xf1¼O{º"

if I cast malloc such as so fileName = (char*)malloc(strlen(argv[i]) * sizeof(char)); I get this allocated in memory:

0x009d8d38 "ÍÍÍÍÍýýýýB"

Considering that my argument is 5 bytes, is malloc allocating more memory then it should or am I just doing this incorrectly?


回答1:


Usually malloc allocates memory in chunks exactly divisible by the paragraph size equal to 16 bytes (that is malloc allocates chunks with a fundamental alignment requirement). However you should not rely on this internal behavior of malloc. Otherwise the behavior is undefined.



来源:https://stackoverflow.com/questions/42283281/is-malloc-allocating-more-memory-then-needed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!