• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EST 16:01
CET 22:01
KST 06:01
  • Home
  • Forum
  • Calendar
  • Streams
  • Liquipedia
  • Features
  • Store
  • EPT
  • TL+
  • StarCraft 2
  • Brood War
  • Smash
  • Heroes
  • Counter-Strike
  • Overwatch
  • Liquibet
  • Fantasy StarCraft
  • TLPD
  • StarCraft 2
  • Brood War
  • Blogs
Forum Sidebar
Events/Features
News
Featured News
TL.net Map Contest #21: Winners2Intel X Team Liquid Seoul event: Showmatches and Meet the Pros10[ASL20] Finals Preview: Arrival13TL.net Map Contest #21: Voting12[ASL20] Ro4 Preview: Descent11
Community News
Starcraft, SC2, HoTS, WC3, returning to Blizzcon!20$5,000+ WardiTV 2025 Championship5[BSL21] RO32 Group Stage3Weekly Cups (Oct 26-Nov 2): Liquid, Clem, Solar win; LAN in Philly2Weekly Cups (Oct 20-26): MaxPax, Clem, Creator win9
StarCraft 2
General
TL.net Map Contest #21: Winners Starcraft, SC2, HoTS, WC3, returning to Blizzcon! RotterdaM "Serral is the GOAT, and it's not close" Weekly Cups (Oct 20-26): MaxPax, Clem, Creator win 5.0.15 Patch Balance Hotfix (2025-10-8)
Tourneys
$5,000+ WardiTV 2025 Championship Constellation Cup - Main Event - Stellar Fest Merivale 8 Open - LAN - Stellar Fest Sea Duckling Open (Global, Bronze-Diamond) $3,500 WardiTV Korean Royale S4
Strategy
Custom Maps
Map Editor closed ?
External Content
Mutation # 498 Wheel of Misfortune|Cradle of Death Mutation # 497 Battle Haredened Mutation # 496 Endless Infection Mutation # 495 Rest In Peace
Brood War
General
BGH Auto Balance -> http://bghmmr.eu/ SnOw's ASL S20 Finals Review [BSL21] RO32 Group Stage Practice Partners (Official) [ASL20] Ask the mapmakers — Drop your questions
Tourneys
[Megathread] Daily Proleagues [BSL21] RO32 Group B - Sunday 21:00 CET [BSL21] RO32 Group A - Saturday 21:00 CET BSL21 Open Qualifiers Week & CONFIRM PARTICIPATION
Strategy
Current Meta How to stay on top of macro? PvZ map balance Soma's 9 hatch build from ASL Game 2
Other Games
General Games
Stormgate/Frost Giant Megathread Nintendo Switch Thread Dawn of War IV ZeroSpace Megathread General RTS Discussion Thread
Dota 2
Official 'what is Dota anymore' discussion
League of Legends
Heroes of the Storm
Simple Questions, Simple Answers Heroes of the Storm 2.0
Hearthstone
Deck construction bug Heroes of StarCraft mini-set
TL Mafia
TL Mafia Community Thread SPIRED by.ASL Mafia {211640}
Community
General
US Politics Mega-thread Russo-Ukrainian War Thread Things Aren’t Peaceful in Palestine YouTube Thread Dating: How's your luck?
Fan Clubs
White-Ra Fan Club The herO Fan Club!
Media & Entertainment
Anime Discussion Thread Movie Discussion! [Manga] One Piece Korean Music Discussion Series you have seen recently...
Sports
2024 - 2026 Football Thread NBA General Discussion MLB/Baseball 2023 TeamLiquid Health and Fitness Initiative For 2023 Formula 1 Discussion
World Cup 2022
Tech Support
SC2 Client Relocalization [Change SC2 Language] Linksys AE2500 USB WIFI keeps disconnecting Computer Build, Upgrade & Buying Resource Thread
TL Community
The Automated Ban List Recent Gifted Posts
Blogs
Saturation point
Uldridge
DnB/metal remix FFO Mick Go…
ImbaTosS
Why we need SC3
Hildegard
Career Paths and Skills for …
TrAiDoS
Reality "theory" prov…
perfectspheres
Our Last Hope in th…
KrillinFromwales
Customize Sidebar...

Website Feedback

Closed Threads



Active: 1272 users

The Big Programming Thread - Page 863

Forum Index > General Forum
Post a Reply
Prev 1 861 862 863 864 865 1032 Next
Thread Rules
1. This is not a "do my homework for me" thread. If you have specific questions, ask, but don't post an assignment or homework problem and expect an exact solution.
2. No recruiting for your cockamamie projects (you won't replace facebook with 3 dudes you found on the internet and $20)
3. If you can't articulate why a language is bad, don't start slinging shit about it. Just remember that nothing is worse than making CSS IE6 compatible.
4. Use [code] tags to format code blocks.
Acrofales
Profile Joined August 2010
Spain18108 Posts
March 22 2017 18:33 GMT
#17241
On March 22 2017 19:03 dsyxelic wrote:
oh then i misinterpreted the question :/ they didnt specify what kind of list it was so I guess we can assume it's either an array implementation or a list by pointers

I went with array cause that seemed simpler

k then thinking of it now with some code

def match(list, s):
start = -1
end = len(list)
while end-start>1:
p = (start+end)/2
if list[p] == s:
return True
if list[p] > s:
end=p
else:
start=p
return False


though of course the comparisons would only work if I had a some other function to compare the characters of the string or the value of the string for alphabetical comparison.

this function would run in O(log n)
total O(m log n), m = size of string s for character comparison

or O(|S| log n) with the way you expressed it

Pretty sure it's not O(m*log n) but rather O(m + log(n)). You only have to walk through the string length a constant number of times if you keep track of the part of the string that you've already matched on both "bounds" of your binary search. Usually string length is completely negligible in comparison to the number of strings you have to look through, and if it's not, you should use a different data structure (like a trie) to solve the problem, and not a sorted array. But given the question was phrased explicitly to include the string length as a parameter, O(m + log(n)) is the best I can come up with.
slmw
Profile Blog Joined October 2010
Finland233 Posts
March 22 2017 18:50 GMT
#17242
On March 23 2017 03:33 Acrofales wrote:
Show nested quote +
On March 22 2017 19:03 dsyxelic wrote:
oh then i misinterpreted the question :/ they didnt specify what kind of list it was so I guess we can assume it's either an array implementation or a list by pointers

I went with array cause that seemed simpler

k then thinking of it now with some code

def match(list, s):
start = -1
end = len(list)
while end-start>1:
p = (start+end)/2
if list[p] == s:
return True
if list[p] > s:
end=p
else:
start=p
return False


though of course the comparisons would only work if I had a some other function to compare the characters of the string or the value of the string for alphabetical comparison.

this function would run in O(log n)
total O(m log n), m = size of string s for character comparison

or O(|S| log n) with the way you expressed it

Pretty sure it's not O(m*log n) but rather O(m + log(n)). You only have to walk through the string length a constant number of times if you keep track of the part of the string that you've already matched on both "bounds" of your binary search. Usually string length is completely negligible in comparison to the number of strings you have to look through, and if it's not, you should use a different data structure (like a trie) to solve the problem, and not a sorted array. But given the question was phrased explicitly to include the string length as a parameter, O(m + log(n)) is the best I can come up with.


If you binary search it character by character, you have to do log N comparisons for each character of the input string. That's O(M*log(N)).
Acrofales
Profile Joined August 2010
Spain18108 Posts
Last Edited: 2017-03-22 19:23:23
March 22 2017 19:18 GMT
#17243
On March 23 2017 03:50 slmw wrote:
Show nested quote +
On March 23 2017 03:33 Acrofales wrote:
On March 22 2017 19:03 dsyxelic wrote:
oh then i misinterpreted the question :/ they didnt specify what kind of list it was so I guess we can assume it's either an array implementation or a list by pointers

I went with array cause that seemed simpler

k then thinking of it now with some code

def match(list, s):
start = -1
end = len(list)
while end-start>1:
p = (start+end)/2
if list[p] == s:
return True
if list[p] > s:
end=p
else:
start=p
return False


though of course the comparisons would only work if I had a some other function to compare the characters of the string or the value of the string for alphabetical comparison.

this function would run in O(log n)
total O(m log n), m = size of string s for character comparison

or O(|S| log n) with the way you expressed it

Pretty sure it's not O(m*log n) but rather O(m + log(n)). You only have to walk through the string length a constant number of times if you keep track of the part of the string that you've already matched on both "bounds" of your binary search. Usually string length is completely negligible in comparison to the number of strings you have to look through, and if it's not, you should use a different data structure (like a trie) to solve the problem, and not a sorted array. But given the question was phrased explicitly to include the string length as a parameter, O(m + log(n)) is the best I can come up with.


If you binary search it character by character, you have to do log N comparisons for each character of the input string. That's O(M*log(N)).


No you don't. You start with the beginning of the string. Once you're in the part of the array where your bounds match the first X characters, you only compare the X+1st character onwards, etc. Don't feel like writing out the code, because it's finicky and you have to deal with lots of corner cases, but I'll sketch it:

Search string: abcd

Array (with color codes for what the binary search checks, and strikethroughs for parts of string that are skipped):
aaaa
aaab
aaac
abbb
abbc
abcd
abce
abdd
addd
adde
addf
bcde
cccc
cccd
ccde
cddd
cdff
daaa
daba
dabc
ddaa
ddbb
dddd

So we start in the middle:
addf > abcd. But a matched, so we remember that
Next up: middle between start and addf: abbc
abbc < abcd. So now we know that everything between abbc and addf starts with a, so we move the search index up. Moreover, the second char matches too: b matched as well. So we remember that, and from now on skip the first char, so next: bdd
bdd > bcd. b is matched, so we know everything between abbc and abdd matches the first two chars. We once again move the search index up. Next test: cd == cd. We are done.

Thus we don't have to check m characters log n times. We have to check a couple of characters log n times, but m characters at most twice.
slmw
Profile Blog Joined October 2010
Finland233 Posts
March 22 2017 20:24 GMT
#17244
Obviously in the uniformly distributed case it is O(log N) as was established earlier in this thread. However in these types of puzzles we're usually talking about the worst case (and the prevailing question in the thread was whether there is anything better than O(M*log N) for the worst case). Your solution is O(M log N) as well in the worst case. "Couple of characters" and "at most twice" certainly isn't true in the general case.
meadbert
Profile Blog Joined October 2010
United States681 Posts
March 22 2017 20:30 GMT
#17245
On March 23 2017 04:18 Acrofales wrote:
Show nested quote +
On March 23 2017 03:50 slmw wrote:
On March 23 2017 03:33 Acrofales wrote:
On March 22 2017 19:03 dsyxelic wrote:
oh then i misinterpreted the question :/ they didnt specify what kind of list it was so I guess we can assume it's either an array implementation or a list by pointers

I went with array cause that seemed simpler

k then thinking of it now with some code

def match(list, s):
start = -1
end = len(list)
while end-start>1:
p = (start+end)/2
if list[p] == s:
return True
if list[p] > s:
end=p
else:
start=p
return False


though of course the comparisons would only work if I had a some other function to compare the characters of the string or the value of the string for alphabetical comparison.

this function would run in O(log n)
total O(m log n), m = size of string s for character comparison

or O(|S| log n) with the way you expressed it

Pretty sure it's not O(m*log n) but rather O(m + log(n)). You only have to walk through the string length a constant number of times if you keep track of the part of the string that you've already matched on both "bounds" of your binary search. Usually string length is completely negligible in comparison to the number of strings you have to look through, and if it's not, you should use a different data structure (like a trie) to solve the problem, and not a sorted array. But given the question was phrased explicitly to include the string length as a parameter, O(m + log(n)) is the best I can come up with.


If you binary search it character by character, you have to do log N comparisons for each character of the input string. That's O(M*log(N)).


No you don't. You start with the beginning of the string. Once you're in the part of the array where your bounds match the first X characters, you only compare the X+1st character onwards, etc. Don't feel like writing out the code, because it's finicky and you have to deal with lots of corner cases, but I'll sketch it:

Search string: abcd

Array (with color codes for what the binary search checks, and strikethroughs for parts of string that are skipped):
aaaa
aaab
aaac
abbb
abbc
abcd
abce
abdd
addd
adde
addf
bcde
cccc
cccd
ccde
cddd
cdff
daaa
daba
dabc
ddaa
ddbb
dddd

So we start in the middle:
addf > abcd. But a matched, so we remember that
Next up: middle between start and addf: abbc
abbc < abcd. So now we know that everything between abbc and addf starts with a, so we move the search index up. Moreover, the second char matches too: b matched as well. So we remember that, and from now on skip the first char, so next: bdd
bdd > bcd. b is matched, so we know everything between abbc and abdd matches the first two chars. We once again move the search index up. Next test: cd == cd. We are done.

Thus we don't have to check m characters log n times. We have to check a couple of characters log n times, but m characters at most twice.

I agree with you in the typical and average case, but the worst case would be O(m*log(n)).
Note that for you algorithm the worst case would be that the string you are looking for is first or last in the list.
Acrofales
Profile Joined August 2010
Spain18108 Posts
March 22 2017 21:04 GMT
#17246
On March 23 2017 05:30 meadbert wrote:
Show nested quote +
On March 23 2017 04:18 Acrofales wrote:
On March 23 2017 03:50 slmw wrote:
On March 23 2017 03:33 Acrofales wrote:
On March 22 2017 19:03 dsyxelic wrote:
oh then i misinterpreted the question :/ they didnt specify what kind of list it was so I guess we can assume it's either an array implementation or a list by pointers

I went with array cause that seemed simpler

k then thinking of it now with some code

def match(list, s):
start = -1
end = len(list)
while end-start>1:
p = (start+end)/2
if list[p] == s:
return True
if list[p] > s:
end=p
else:
start=p
return False


though of course the comparisons would only work if I had a some other function to compare the characters of the string or the value of the string for alphabetical comparison.

this function would run in O(log n)
total O(m log n), m = size of string s for character comparison

or O(|S| log n) with the way you expressed it

Pretty sure it's not O(m*log n) but rather O(m + log(n)). You only have to walk through the string length a constant number of times if you keep track of the part of the string that you've already matched on both "bounds" of your binary search. Usually string length is completely negligible in comparison to the number of strings you have to look through, and if it's not, you should use a different data structure (like a trie) to solve the problem, and not a sorted array. But given the question was phrased explicitly to include the string length as a parameter, O(m + log(n)) is the best I can come up with.


If you binary search it character by character, you have to do log N comparisons for each character of the input string. That's O(M*log(N)).


No you don't. You start with the beginning of the string. Once you're in the part of the array where your bounds match the first X characters, you only compare the X+1st character onwards, etc. Don't feel like writing out the code, because it's finicky and you have to deal with lots of corner cases, but I'll sketch it:

Search string: abcd

Array (with color codes for what the binary search checks, and strikethroughs for parts of string that are skipped):
aaaa
aaab
aaac
abbb
abbc
abcd
abce
abdd
addd
adde
addf
bcde
cccc
cccd
ccde
cddd
cdff
daaa
daba
dabc
ddaa
ddbb
dddd

So we start in the middle:
addf > abcd. But a matched, so we remember that
Next up: middle between start and addf: abbc
abbc < abcd. So now we know that everything between abbc and addf starts with a, so we move the search index up. Moreover, the second char matches too: b matched as well. So we remember that, and from now on skip the first char, so next: bdd
bdd > bcd. b is matched, so we know everything between abbc and abdd matches the first two chars. We once again move the search index up. Next test: cd == cd. We are done.

Thus we don't have to check m characters log n times. We have to check a couple of characters log n times, but m characters at most twice.

I agree with you in the typical and average case, but the worst case would be O(m*log(n)).
Note that for you algorithm the worst case would be that the string you are looking for is first or last in the list.


Hmm, you're right. I guess if you have something like:

aaaa

and your array is:

aaaa
aaab
aaac
etc.

You have to check m characters log n times, because you can never establish the baseline. Didn't think that one through. You are completely right.
dsyxelic
Profile Joined May 2010
United States1417 Posts
March 22 2017 22:25 GMT
#17247
thanks yall
was pretty fun thinking about this problem the last 2 days and definitely learned alot. especially about learning to understand the question in the first place x.x
TL/SKT
Deleted User 3420
Profile Blog Joined May 2003
24492 Posts
March 26 2017 14:20 GMT
#17248
Going over quiz for wednesday. It has this question

+ Show Spoiler +

What is wrong with the following code?

#include <stdio.h>
#include <stdlib.h>
int *get_val(int y) {
int x = 200;
x += y;
return &x;
}
int main() {
int *p, y = 10;
p = get_val(y);
printf("%d\n", *p);
exit(0);
}



I wasn't sure so I ran the code. Compiler gave me a warning that it returns the address of a local variable (though the program works anyways). I am guessing the correct way to do this, if you don't want to use a global variable, is to pass a pointer to whatever variable you want to return back? So, like, I would have defined int x in main, pass the pointer of x to the function along with y, and then return the address of x?

I have another question as well. Why is this actually a problem? If we do "p = get_val(y);", is it even possible for something to sneak in there and mess with the memory that held our local variable x in that time?
waffelz
Profile Blog Joined June 2012
Germany711 Posts
Last Edited: 2017-03-26 14:50:32
March 26 2017 14:35 GMT
#17249
On March 26 2017 23:20 travis wrote:
Going over quiz for wednesday. It has this question

+ Show Spoiler +

What is wrong with the following code?

#include <stdio.h>
#include <stdlib.h>
int *get_val(int y) {
int x = 200;
x += y;
return &x;
}
int main() {
int *p, y = 10;
p = get_val(y);
printf("%d\n", *p);
exit(0);
}



I wasn't sure so I ran the code. Compiler gave me a warning that it returns the address of a local variable (though the program works anyways). I am guessing the correct way to do this, if you don't want to use a global variable, is to pass a pointer to whatever variable you want to return back? So, like, I would have defined int x in main, pass the pointer of x to the function along with y, and then return the address of x?

I have another question as well. Why is this actually a problem? If we do "p = get_val(y);", is it even possible for something to sneak in there and mess with the memory that held our local variable x in that time?


Not sure, but:
Since it is a local variable, the moment the programm exists the function, the memory adress still holds the value but is no longer protected and could be used to store a differerent value by another programm and therefore could contain something completely different. Propably unlikely that this happens in the given example but anyways... I feel like there are a lot of coding questions that are just irrelevant as soon as you follow certain best practices... at least for my interview for an internship a while back it was.
RIP "The big travis CS degree thread", taken from us too soon | Honourable forum princess, defended by Rebs-approved white knights
beg
Profile Blog Joined May 2010
991 Posts
Last Edited: 2017-03-26 14:42:36
March 26 2017 14:38 GMT
#17250
On March 26 2017 23:20 travis wrote:
Going over quiz for wednesday. It has this question

+ Show Spoiler +

What is wrong with the following code?

#include <stdio.h>
#include <stdlib.h>
int *get_val(int y) {
int x = 200;
x += y;
return &x;
}
int main() {
int *p, y = 10;
p = get_val(y);
printf("%d\n", *p);
exit(0);
}



I wasn't sure so I ran the code. Compiler gave me a warning that it returns the address of a local variable (though the program works anyways). I am guessing the correct way to do this, if you don't want to use a global variable, is to pass a pointer to whatever variable you want to return back? So, like, I would have defined int x in main, pass the pointer of x to the function along with y, and then return the address of x?

I have another question as well. Why is this actually a problem? If we do "p = get_val(y);", is it even possible for something to sneak in there and mess with the memory that held our local variable x in that time?

I'm not even sure what this code is supposed to do. Why would you do some arithmetic with x and then only return x's adress? I can't make sense out of this program's intention.

If the code is intended to add 200 to y and return the result, then the mistake is that we're returning x's adress instead of its actual value
Deleted User 3420
Profile Blog Joined May 2003
24492 Posts
Last Edited: 2017-03-26 14:53:53
March 26 2017 14:41 GMT
#17251
On March 26 2017 23:38 beg wrote:
Show nested quote +
On March 26 2017 23:20 travis wrote:
Going over quiz for wednesday. It has this question

+ Show Spoiler +

What is wrong with the following code?

#include <stdio.h>
#include <stdlib.h>
int *get_val(int y) {
int x = 200;
x += y;
return &x;
}
int main() {
int *p, y = 10;
p = get_val(y);
printf("%d\n", *p);
exit(0);
}



I wasn't sure so I ran the code. Compiler gave me a warning that it returns the address of a local variable (though the program works anyways). I am guessing the correct way to do this, if you don't want to use a global variable, is to pass a pointer to whatever variable you want to return back? So, like, I would have defined int x in main, pass the pointer of x to the function along with y, and then return the address of x?

I have another question as well. Why is this actually a problem? If we do "p = get_val(y);", is it even possible for something to sneak in there and mess with the memory that held our local variable x in that time?

I'm not even sure what this code is supposed to do. Why would you do some arithmetic with x and then only return x's adress? I can't make sense out of this program's intention.


I don't think it's meant for practical application


ok how about this question:

". Name one advantage of initializing pointer variables to NULL?"

Is an advantage of doing this, that if you don't initialize them to null then if your code doesn't assign them to an address somewhere, and you try to grab the pointer, it may really mess up your program and be hard to debug?

I suppose also if your program is using memory allocation and you free the pointer, it will be no problem if the pointer was initialized to null, but a big problem if it was never initialized.
waffelz
Profile Blog Joined June 2012
Germany711 Posts
March 26 2017 14:52 GMT
#17252
On March 26 2017 23:41 travis wrote:
Show nested quote +
On March 26 2017 23:38 beg wrote:
On March 26 2017 23:20 travis wrote:
Going over quiz for wednesday. It has this question

+ Show Spoiler +

What is wrong with the following code?

#include <stdio.h>
#include <stdlib.h>
int *get_val(int y) {
int x = 200;
x += y;
return &x;
}
int main() {
int *p, y = 10;
p = get_val(y);
printf("%d\n", *p);
exit(0);
}



I wasn't sure so I ran the code. Compiler gave me a warning that it returns the address of a local variable (though the program works anyways). I am guessing the correct way to do this, if you don't want to use a global variable, is to pass a pointer to whatever variable you want to return back? So, like, I would have defined int x in main, pass the pointer of x to the function along with y, and then return the address of x?

I have another question as well. Why is this actually a problem? If we do "p = get_val(y);", is it even possible for something to sneak in there and mess with the memory that held our local variable x in that time?

I'm not even sure what this code is supposed to do. Why would you do some arithmetic with x and then only return x's adress? I can't make sense out of this program's intention.


I don't think it's meant for practical application


ok how about this question:

". Name one advantage of initializing pointer variables to NULL?"

Is an advantage of doing this, that if you don't initialize them to null then if your code doesn't assign them to an address somewhere, and you try to grab the pointer, it may really mess up your program and be hard to debug?


Yes. This is just a way to minimise the risk of stupid errors. If you don't initialize them with NULL, they could point to pretty much anything and can make debugging a mess since it can lead to inconsistent crashes.
RIP "The big travis CS degree thread", taken from us too soon | Honourable forum princess, defended by Rebs-approved white knights
beg
Profile Blog Joined May 2010
991 Posts
March 26 2017 14:52 GMT
#17253
Yea definitely. Did you see the edit of my last post?
Deleted User 3420
Profile Blog Joined May 2003
24492 Posts
March 26 2017 14:56 GMT
#17254
On March 26 2017 23:38 beg wrote:
Show nested quote +
On March 26 2017 23:20 travis wrote:
Going over quiz for wednesday. It has this question

+ Show Spoiler +

What is wrong with the following code?

#include <stdio.h>
#include <stdlib.h>
int *get_val(int y) {
int x = 200;
x += y;
return &x;
}
int main() {
int *p, y = 10;
p = get_val(y);
printf("%d\n", *p);
exit(0);
}



I wasn't sure so I ran the code. Compiler gave me a warning that it returns the address of a local variable (though the program works anyways). I am guessing the correct way to do this, if you don't want to use a global variable, is to pass a pointer to whatever variable you want to return back? So, like, I would have defined int x in main, pass the pointer of x to the function along with y, and then return the address of x?

I have another question as well. Why is this actually a problem? If we do "p = get_val(y);", is it even possible for something to sneak in there and mess with the memory that held our local variable x in that time?

I'm not even sure what this code is supposed to do. Why would you do some arithmetic with x and then only return x's adress? I can't make sense out of this program's intention.

If the code is intended to add 200 to y and return the result, then the mistake is that we're returning x's adress instead of its actual value


Why is that a problem? P is a pointer.
I mean we could make P an int and change our function and it would probably make more sense, but I don't see why this is a mistake as is.
beg
Profile Blog Joined May 2010
991 Posts
Last Edited: 2017-03-26 15:40:12
March 26 2017 15:24 GMT
#17255
Well shit, I just realized I never fiddled around with pointers to funciton. Nevermind. I'm playing around with it now.

EDIT: Yea you explained it correct in the same post where you asked the question
Blitzkrieg0
Profile Blog Joined August 2010
United States13132 Posts
March 26 2017 15:37 GMT
#17256
On March 26 2017 23:20 travis wrote:
is it even possible for something to sneak in there and mess with the memory that held our local variable x in that time?


Imagine if you did something like this instead:

#include <stdio.h>
#include <stdlib.h>
int *get_val(int y) {
int x = 200;
x += y;
return &x;
}
int main() {
int *p, y = 10;
int *w;
p = get_val(y);
w = get_val(100);
printf("%d%d\n", *p, *w);
exit(0);
}


Pretty sure that will break and you can figure out why its bad.
I'll always be your shadow and veil your eyes from states of ain soph aur.
Deleted User 3420
Profile Blog Joined May 2003
24492 Posts
March 26 2017 15:45 GMT
#17257
Oh blitz that's an excellent example, thank you.

Just to make sure I am on the right page here, the poblem is that when we dereference p and w in our print statement, they are both going to print from the same address, which currently holds the result of get_val(100) ?
Blitzkrieg0
Profile Blog Joined August 2010
United States13132 Posts
Last Edited: 2017-03-26 16:13:17
March 26 2017 16:11 GMT
#17258
On March 27 2017 00:45 travis wrote:
Oh blitz that's an excellent example, thank you.

Just to make sure I am on the right page here, the poblem is that when we dereference p and w in our print statement, they are both going to print from the same address, which currently holds the result of get_val(100) ?


The real problem is undefined behavior. When you're programming you have an expected result and this program does not always return the expected result because you're referencing a pointer that is out of scope. Because the pointer is declared in the function call, it is out of scope after the function ends and can be overwritten.

In the example you provided the print statement was immediately done and it probably wasn't a issue (note that this is still bad, the fact that it could have been wrong is still a problem even though it likely never happens).

In my example, the value is overwritten and the wrong value is printed.

In another example, you could get that memory allocated to another process and cause a segfault by trying to access memory in another process.

Bottom line is that you don't want to write code that can have undefined behavior. You can't know what will happen because it will depend on how the operating system assigns memory when the program is run.
I'll always be your shadow and veil your eyes from states of ain soph aur.
Mr. Wiggles
Profile Blog Joined August 2010
Canada5894 Posts
March 26 2017 16:31 GMT
#17259
On March 27 2017 00:45 travis wrote:
Oh blitz that's an excellent example, thank you.

Just to make sure I am on the right page here, the poblem is that when we dereference p and w in our print statement, they are both going to print from the same address, which currently holds the result of get_val(100) ?

Travis, have you learnt about memory layouts and the call stack yet? This is essentially the underlying reason for why the given program results in undefined behaviour.

https://en.wikipedia.org/wiki/Call_stack

When you call a function, we increment the stack pointer to make room for several things, including local variables of the function. So in your example, we're going to have some address on the stack which points to the local variable 'x'.

When the function terminates, we're going to decrement the stack pointer to where it was before the function was called. Therefore, referring to any of the locals from the function after we've returned now results in undefined behaviour.

Depending on what the function is actually supposed to do, I think the following might have been what was desired:

+ Show Spoiler +

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

int * get_val(int y)
{
static int x = 200;
x += y;
return &x;
}

int main()
{
int *p, y = 10;
p = get_val(y);
printf("%d\n", *p);
exit(0);
}

you gotta dance
Acrofales
Profile Joined August 2010
Spain18108 Posts
March 26 2017 16:44 GMT
#17260
Regardless of what that code does and is supposed to do, that is some absolutely horrendous coding. I understand asking you general questions that require you to understand C code, but does it really have to be so incredibly shitty?
Prev 1 861 862 863 864 865 1032 Next
Please log in or register to reply.
Live Events Refresh
LAN Event
18:00
Day 3: Ursa 2v2, FFA
SteadfastSC393
IndyStarCraft 177
LiquipediaDiscussion
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
mouzHeroMarine 522
SteadfastSC 393
White-Ra 235
IndyStarCraft 177
UpATreeSC 134
ProTech123
Railgan 61
ROOTCatZ 40
StarCraft: Brood War
Shuttle 451
Bonyth 77
ivOry 12
Dota 2
Dendi1030
Counter-Strike
pashabiceps1118
Foxcn172
Super Smash Bros
Liquid`Ken5
Heroes of the Storm
Liquid`Hasu516
Other Games
Beastyqt756
fl0m662
shahzam465
FrodaN419
KnowMe182
Pyrionflax172
ArmadaUGS138
C9.Mang0114
ToD87
Mew2King75
Trikslyr53
OptimusSC21
Organizations
Counter-Strike
PGL164
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 20 non-featured ]
StarCraft 2
• Adnapsc2 11
• Reevou 10
• Dystopia_ 3
• Kozan
• sooper7s
• AfreecaTV YouTube
• Migwel
• LaughNgamezSOOP
• intothetv
• IndyKCrew
StarCraft: Brood War
• STPLYoutube
• ZZZeroYoutube
• BSLYoutube
Dota 2
• C_a_k_e 2989
• Ler85
League of Legends
• TFBlade969
Other Games
• imaqtpie1345
• WagamamaTV341
• Scarra323
• Shiphtur216
Upcoming Events
OSC
59m
Replay Cast
1h 59m
OSC
14h 59m
LAN Event
17h 59m
Korean StarCraft League
1d 5h
CranKy Ducklings
1d 12h
LAN Event
1d 17h
IPSL
1d 20h
dxtr13 vs OldBoy
Napoleon vs Doodle
BSL 21
1d 22h
Gosudark vs Kyrie
Gypsy vs Sterling
UltrA vs Radley
Dandy vs Ptak
Replay Cast
2 days
[ Show More ]
Sparkling Tuna Cup
2 days
WardiTV Korean Royale
2 days
LAN Event
2 days
IPSL
2 days
JDConan vs WIZARD
WolFix vs Cross
BSL 21
2 days
spx vs rasowy
HBO vs KameZerg
Cross vs Razz
dxtr13 vs ZZZero
Replay Cast
3 days
Wardi Open
3 days
WardiTV Korean Royale
4 days
Replay Cast
5 days
Kung Fu Cup
5 days
Classic vs Solar
herO vs Cure
Reynor vs GuMiho
ByuN vs ShoWTimE
Tenacious Turtle Tussle
6 days
The PondCast
6 days
RSL Revival
6 days
Solar vs Zoun
MaxPax vs Bunny
Kung Fu Cup
6 days
WardiTV Korean Royale
6 days
Liquipedia Results

Completed

BSL 21 Points
SC4ALL: StarCraft II
Eternal Conflict S1

Ongoing

C-Race Season 1
IPSL Winter 2025-26
KCM Race Survival 2025 Season 4
SOOP Univ League 2025
YSL S2
IEM Chengdu 2025
PGL Masters Bucharest 2025
Thunderpick World Champ.
CS Asia Championships 2025
ESL Pro League S22
StarSeries Fall 2025
FISSURE Playground #2
BLAST Open Fall 2025
BLAST Open Fall Qual
Esports World Cup 2025

Upcoming

BSL Season 21
SLON Tour Season 2
BSL 21 Non-Korean Championship
Acropolis #4
HSC XXVIII
RSL Offline Finals
WardiTV 2025
RSL Revival: Season 3
Stellar Fest
META Madness #9
BLAST Bounty Winter 2026: Closed Qualifier
eXTREMESLAND 2025
ESL Impact League Season 8
SL Budapest Major 2025
BLAST Rivals Fall 2025
TLPD

1. ByuN
2. TY
3. Dark
4. Solar
5. Stats
6. Nerchio
7. sOs
8. soO
9. INnoVation
10. Elazer
1. Rain
2. Flash
3. EffOrt
4. Last
5. Bisu
6. Soulkey
7. Mini
8. Sharp
Sidebar Settings...

Advertising | Privacy Policy | Terms Of Use | Contact Us

Original banner artwork: Jim Warren
The contents of this webpage are copyright © 2025 TLnet. All Rights Reserved.