Writing more characters than malloced. Why does it

2020-04-16 19:26发布

Why does the following work and not throw some kind of segmentation fault?

char *path = "/usr/bin/";
char *random = "012";

// path + random + \0
// so its malloc(13), but I get 16 bytes due to memory alignment (im on 32bit)
newPath = (char *) malloc(strlen(path) + strlen(random) + 1);

strcat(newPath, path);
strcat(newPath, "random");
// newPath is now: "/usr/bin/012\0" which makes 13 characters.

However, if I add

strcat(newPath, "RANDOMBUNNIES");

shouldn't this call fail, because strcat uses more memory than allocated? Consequently, shouldn't

free(newPath)

also fail because it tries to free 16 bytes but I used 26 bytes ("/usr/bin/012RANDOMBUNNIES\0")?

Thank you so much in advance!

9条回答
霸刀☆藐视天下
2楼-- · 2020-04-16 19:52

Most often this kind of overrun problems doesn't make your program explode in a cloud of smoke and the smell of burnt sulphur. It's more subtle: the variable that is allocated after the overrun variable will be altered, causing unexplainable and seemingly random behavior of the program later on.

查看更多
Ridiculous、
3楼-- · 2020-04-16 19:54

It will fail and not fail at random, depending on the availability of the memory just after the malloc'd memory.

Also when you want to concat random you shouldn't be putting in quotes. that should be

strcat(newPath, random);
查看更多
别忘想泡老子
4楼-- · 2020-04-16 19:55

Segmentation fault generally occurs because of accessing the invalid memory section. Here it won't give error(Segmentation fault) because you can still access memory. However you are overwriting other memory locations which is undefined behavior, your code runs fine.

查看更多
登录 后发表回答